【问题标题】:Sql Query with not in clause of subquery to LINQ query带有 not in 子查询子句的 SQL 查询到 LINQ 查询
【发布时间】:2021-01-25 18:32:25
【问题描述】:
select * from user_user_connection
where userid_from = 3464 and
userid_to not in
(select userid_from from
user_user_connection
where userid_to = 3464);
大家好,我是实体框架的新手。
我正在尝试将此查询转换为无法理解如何使用 not in 子句编写子查询的 LINQ 查询。
还有哪个更适合加入或包括?
【问题讨论】:
标签:
c#
entity-framework
linq
sql-to-linq-conversion
【解决方案1】:
这个
from a in user_user_connection
join b in user_user_connection on
new {From=a.userid_to, To=a.userid_from} equals new {From=b.userid_from, To=b.userid_to} into c
from d in c.DefaultIfEmpty()
where d == null
select a;
类似于
select a.*
from user_user_connection a
left join user_user_connection b on a.userid_to = b.userid_from and a.userid_from = b.userid_to
where b.userid_from is null
应该匹配你的 not in 查询。
如果你想要一个特定的userid_from,你可以在其中添加另一个
from a in user_user_connection
where a.userid_from == 3464
join b in user_user_connection on
new {From=a.userid_to, To=a.userid_from} equals new {From=b.userid_from, To=b.userid_to} into c
from d in c.DefaultIfEmpty()
where d == null
select a;
【解决方案2】:
可能是这样的:
var list = userConnection.Where(user => user.useridto == 3464).Select(user => user.userid_from).ToList();
var list2 = userConnection.Where(user => !list.Contains(user.userid_to));
可能可以改进,因为包含需要相当长的时间(也许将列表放入哈希集中?)
【解决方案3】:
这应该可行:
var query =
from uc in ctx.user_user_connection
where uc.userid_from = 3464 &&
!(from uc2 in ctx.user_user_connection
where uc2.userid_to = 3464
select uc2.userid_from).Contains(uc.userid_to)
select uc;
或通过EXISTS
var query =
from uc in ctx.user_user_connection
where uc.userid_from = 3464 &&
!(from uc2 in ctx.user_user_connection
where uc2.userid_to = 3464 && uc.userid_to == uc2.userid_from
select uc2).Any()
select uc;
Ov 通过LEFT JOIN
var query =
from uc in ctx.user_user_connection
from uc2 in ctx.user_user_connection
.Where(uc2 => uc2.userid_from == 3464 && uc.userid_to == uc2.userid_from)
.DefaultIfEmpty()
where uc.userid_from = 3464 && uc2 == null
select uc;