我有一个查询,在SQL中看起来像这样:
SELECT *
FROM ORDERS o, CUSTOMERS c
WHERE
(several conditions)
AND o.NUMBER NOT IN
(SELECT o.NUMBER
FROM ORDERS o, CUSTOMERS c
WHERE
(exactly the same conditions as above)
GROUP BY o.NUMBER
HAVING COUNT(*) > 1)
我在LINQ中尝试这样做并没有返回与SQL查询相同的结果。这就是我正在做的事情:
var query = (from o in context.ORDERS
from c in context.CUSTOMERS
where (bunch of conditions) &&
(from o in context.ORDERS
from c in context.CUSTOMERS
where (bunch of conditions)
group o by o.NUMBER into grp
where grp.Count() > 1
select grp.Key).Contains(o.NUMBER) == false
select new { o, c }).ToList();
我想知道的是:
答案 0 :(得分:1)
您提供的查询应该完全相同,因此我怀疑您的条件翻译不好。在案例敏感性或可空性方面很可能是一个错误。
您正在进行矩阵连接(或笛卡尔连接),然后使用where子句进行过滤。您应该将此转换为正确的连接(您的原始SQL也应该已经完成此操作,但它没有使用" on" t)。条款。由于你没有提供where条件,我无法帮助你,但无论如何这里是一个半优化的版本:
var query = (from o in context.ORDERS
from c in context.CUSTOMERS
where (bunch of conditions)
group new {o,c} by o.NUMBER into grp
where grp.Count() == 1
select grp)
.SelectMany(x=>x)
.ToList();