【发布时间】:2020-12-31 07:24:30
【问题描述】:
我正在尝试将我的 SQL 语法转换为 LINQ 查询,但我遇到了子查询问题。 我想在表中选择带有 Id 的最大日期时间作为另一个选择命令的子查询,但我不知道下面的代码是对还是错。 我在 Sql 中有什么
select ap.* ,aph.Lat as 'personLat',aph.Lng as 'personLng',l.cityId,l.Lat as 'LifecenterLat',l.lng as 'LifecenterLng',l.Id as 'LifeCenterId'
from Applicant ap
inner join ApplicantAddressHistory aph on ap.Id = aph.ApplicantId
inner join LifePlusCenter l on aph.CityId = l.CityId
Where ap.FamilyRoleTypeId = '82e26080-fda6-4396-946c-40d0e267f1f3' and aph.CreatedDate in (select max(CreatedDate) from ApplicantAddressHistory
where ApplicantAddressHistory.ApplicantId = ap.Id)
order by ap.NationalityCode
以及我在 linq 中尝试过的内容
var innerJoinMultipleTables = from app in db.Applicant.Where(x => x.FamilyRoleTypeId == Guid.Parse("82e26080-fda6-4396-946c-40d0e267f1f3"))
join aph in db.ApplicantAddressHistory on app.Id equals aph.ApplicantId
where aph.CreatedDate == db.ApplicantAddressHistory.Max(x => x.CreatedDate && x.Id=aph.Id)
join l in db.LifePlusCenter on aph.CityId equals l.CityId
let centerLat = l.Lat
let centerLng = l.Lng
orderby app.NationalityCode
select new { app, aph.Lat, aph.Lng, l.CityId, l.Branch, centerLat, centerLng };
没有下面这行代码,我的 linq 可以正常工作。
where aph.CreatedDate == db.ApplicantAddressHistory.Max(x => x.CreatedDate && x.Id=aph.Id)
我在 Linq 中需要像下面这样的代码作为子查询
select max(CreatedDate) from ApplicantAddressHistory where ApplicantAddressHistory.ApplicantId = '9836CEC4-EDCB-492C-9899-DF4279210CD2'
我终于试过了,它成功了,但不知道它的正确方法?!
var innerJoinMultipleTables = from app in db.Applicant.Where(x => x.FamilyRoleTypeId == Guid.Parse("82e26080-fda6-4396-946c-40d0e267f1f3"))
join aph in db.ApplicantAddressHistory on app.Id equals aph.ApplicantId
let rept_max = (from c in db.ApplicantAddressHistory
where c.Id == app.Id
select c.CreatedDate).Max()
where aph.CreatedDate == rept_max
join l in db.LifePlusCenter on aph.CityId equals l.CityId
let centerLat = l.Lat
let centerLng = l.Lng
orderby app.NationalityCode
select new { app, aph.Lat, aph.Lng, l.CityId, l.Branch, centerLat, centerLng };
【问题讨论】:
-
我有一个关于 LINQ 查询的问题:子查询 where 语句是否使用正确的
ApplicantAddressHistory列来获取最大日期?我认为这应该是正确的:where c.ApplicantId == app.Id
标签: sql linq linq-to-sql