带有子连接和子查询的SQL到LINQ

时间:2017-02-01 22:38:52

标签: c# entity-framework linq sql-to-linq-conversion

我对LINQ很新,在将此SQL转换为LINQ时遇到问题。任何人都可以帮我实现这个目标吗?

Select DISTINCT u.ID from 
(Select x.ID from table1 x where x.Info = 0) u
where u.ID not in 
(select c.ID from table1 c where c.Info = 1)

我有一张桌子1

ID Info 1 0 1 1 1 0 2 0 3 1 3 0 4 0 5 1

我想返回所有Info = 0的记录,所以上表的输出就是 2,4,

请分享一些见解

3 个答案:

答案 0 :(得分:1)

这将只返回所有INFO = 0

的ID
In [8]:
df['a'].fillna(0).astype(int)

Out[8]:
0    1
1    0
2    3
3    4
Name: a, dtype: int32

答案 1 :(得分:0)

var innerQuery = context.Table1.where(z=>z.Info == 1).Select(z=>z.ID)
var query = context.Table1.where(z=>z.Info == 0 && !innerQuery.Any(x=>x==z.ID)).Select(z=>z.ID)

答案 2 :(得分:0)

当你选择Octaviocci的答案时,我会指出LINQ看起来像SQL,而不是那些使用像他这样的Lambda表达式的LINQ。以下是当您更熟悉T-SQL时,常规Linq语句的样子:

var nonEquijoinQuery = (from a in table1
                        let b = from c in table1
                            where c.Info == 1
                            select c.ID
                        where a.Info == 0 && b.Contains(a.ID) == false
                        select a.ID).Distinct();