【问题标题】:Tried converting sql query to linq, however, I get different results尝试将 sql 查询转换为 linq,但是,我得到了不同的结果
【发布时间】:2011-11-21 08:00:42
【问题描述】:

我正在尝试将 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

测试表:

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 and 11)

我的想法是我试图获取与 rec_id 完全相同的 set_id (set_id 11: (25,32)),但是 (set_id 10: (1,25,32)) 不是完全匹配。

我添加了两张图片,显示了使用 LinqPad 的结果集:

SqlStatmentWithResultSet
LinqStatmentWihtResultSet

提前感谢您的帮助...

【问题讨论】:

  • 在您的 LINQ 语句中,在子查询中,您有“!recIdList.Contains(u.Rec_id)”。这不应该是对 k.Rec_id 的测试吗?
  • 非常感谢 :$ ... 做到了 :) :$
  • 如何将问题标记为已回答?这是我在 stackoverflow 中的第二个问题:O
  • 我现在将其发布为答案,因为它确实解决了问题。

标签: linq entity-framework linq-to-sql


【解决方案1】:

在您的 LINQ 语句中,在子查询中,您有“!recIdList.Contains(u.Rec_id)”。这不应该是对 k.Rec_id 的测试吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2013-02-24
    • 2012-07-05
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多