LINQ - 子查询或LEFT OUTER JOIN?

时间:2018-04-09 14:42:10

标签: linq

我正在尝试优化我的LINQ查询性能,并且我注意到生成了很多LEFT OUTER JOIN。我知道在SQL中,在某些情况下,单行子查询比等效的LEFT OUTER JOIN工作得更好。

例如:

查询1:

select f.FacilityName, p.Id PatientId, u.DOB, (select u2.NameComputed from adm.Staffs s inner join dbo.AspNetUsers u2 on s.UserId = u2.Id where s.Id = p.StaffId) AssignedTo
from ptn.Patients p
inner join dbo.AspNetUsers u on p.UserId = u.Id
inner join hco.Hcos f on p.HcoId = f.Id
where p.IsRemoved = 0

查询2:

select f.FacilityName, p.Id PatientId, u.DOB, u2.NameComputed
from ptn.Patients p
inner join dbo.AspNetUsers u on p.UserId = u.Id
inner join hco.Hcos f on p.HcoId = f.Id
left outer join adm.Staffs s on p.StaffId = s.Id
left outer join dbo.AspNetUsers u2 on s.UserId = u2.Id
where p.IsRemoved = 0

查询1只需不到一秒钟。查询2大约需要45秒。如果我想确保LINQ的结构能够在某些情况下利用这一点,那么我该怎样做呢?也就是说,有没有办法编写一个产生子查询而不是LEFT OUTER JOIN的LINQ语句?

0 个答案:

没有答案