我正在尝试将sql语句转换为linq,但也许我做错了,因为我得到了不同的结果。我在LinqPad尝试我的linq语句。
这是我的sql语句:
SELECT set_id
FROM TestTable
WHERE rec_id In (25,32)
AND set_id NOT IN
(
SELECT x.set_id FROM TestTable x
WHERE x.rec_id NOT IN(25,32)
)
GROUP BY set_id
HAVING COUNT(set_id) = 2
Linq声明:
var recIdList = new List<int?>() { 25,32};
var query = from u in TestTables
where
(
recIdList.Contains(u.Rec_id) &&
!(from k in TestTables
where !recIdList.Contains(u.Rec_id)
select k.Set_id).Contains(u.Set_id)
)
group u by u.Set_id into userGroup
where userGroup.Count() == recIdList.Count
select userGroup.Key;
query.Dump();
TestTables.Dump();
Linq生成的SQL查询:
-- Region Parameters
DECLARE @p0 Int = 25
DECLARE @p1 Int = 32
DECLARE @p2 Int = 25
DECLARE @p3 Int = 32
DECLARE @p4 Int = 2
-- EndRegion
SELECT [t2].[set_id]
FROM (
SELECT COUNT(*) AS [value], [t0].[set_id]
FROM [TestTable] AS [t0]
WHERE ([t0].[rec_id] IN (@p0, @p1)) AND (NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [TestTable] AS [t1]
WHERE ([t1].[set_id] = [t0].[set_id]) AND (NOT ([t0].[rec_id] IN (@p2, @p3)))
)))
GROUP BY [t0].[set_id]
) AS [t2]
WHERE [t2].[value] = @p4
TestTable的:
Create Table TestTable
(
set_id int,
rec_id int
)
Insert Into TestTable (set_id, rec_id) Values(10, 1)
Insert Into TestTable (set_id, rec_id) Values(10, 25)
Insert Into TestTable (set_id, rec_id) Values(10, 32)
Insert Into TestTable (set_id, rec_id) Values(20, 61)
Insert Into TestTable (set_id, rec_id) Values(20, 90)
Insert Into TestTable (set_id, rec_id) Values(30, 77)
Insert Into TestTable (set_id,rec_id) Values(11,25)
Insert Into TestTable (set_id,rec_id) Values(11,32)
GO
我的Sql查询的结果:set_id 11
我的Linq查询的结果:set_id(10和11)
我的想法是尝试获取rec_id正好的set_id(set_id 11:(25,32)),但是(set_id 10:(1,25,32))不是完全匹配。< / p>
我添加了两张图片,显示了使用LinqPad的结果集:
SqlStatmentWithResultSet
LinqStatmentWihtResultSet
先谢谢你的帮助......
答案 0 :(得分:0)
在LINQ语句中,在子查询中,您有“!recIdList.Contains(u.Rec_id)”。这不应该测试k.Rec_id吗?