如何将包含INNER JOIN,LEFT JOIN和GROUP BY的查询转换为类似的linq2sql查询?

时间:2010-10-11 00:21:09

标签: c# linq linq-to-sql

我正在尝试将以下T-SQL查询转换为linq2sql。无论我做什么,它都会将它翻译成一些带有交叉连接的令人讨厌的东西。有什么建议吗?

给出表A,B,C

SELECT A.Id, A.Name, Pool.Total
FROM A
INNER JOIN B ON A.Id = B.AId
LEFT JOIN (
SELECT AId,
SUM(Quantity) as Total
FROM C 
GROUP BY AId) AS Pool ON A.Id = C.AId
WHERE Pool.Total < B.Threshold

1 个答案:

答案 0 :(得分:1)

我写了一个LINQ查询,确实转换为APPLY,但执行计划看起来相同,批处理中的查询成本是50/50 ,所以我想说翻译的查询是相同(或是同义词)。

linq查询

from a in As 
join b in Bs on a.ID equals b.AID 
join  pool in (from c in Cs
                group c by c.AId into cG
                select new {AID = cG.Key,Total = cG.Sum(c=>c.Quantity)} ) on a.ID equals pool.AID into poolG
from pool in poolG.DefaultIfEmpty()
where pool.Total<b.Threshold 
select new {a.ID, a.Name, pool.Total}