我正在尝试映射一个自连接,其中必须过滤正确的表,例如像这样的 SQL:
select t2.* from table t
left join table t2
on t2.parentID = t.ID and t2.active=1;
如果我想过滤 left 表,我可以弄清楚语法:
// works
var query = from t in table
where t.active= 1
join t2 in table
on t.parentID equals t2.ID into joined
from r in joined.DefaultIfEmpty() ...
但我不知道如何过滤正确的表格。好像应该是这样的……
// does not work
var query = from t in table
join t2 in table
where t.field = 1
on t.parentID equals t2.ID into joined
from r in joined.DefaultIfEmpty() ...
(无效...join
不能有 where)。有关于使用多个 from 子句的讨论,但是如果我创建了多个 from 子句,那么我可以在第二个子句中添加一个 where
,我不知道如何加入它们的结果到一个新的临时表中。
我不能只在连接后添加一个“where”;必须先过滤右表,否则会发生匹配,末尾的 where
子句将从左表中删除我希望在输出中显示的行。也就是说,输出应该包含从过滤后的右表中没有任何匹配项的行。所以我需要在连接之前过滤正确的表。
最佳答案
我认为您正在寻求这样做:
var query = from t in table
join t2 in
(from t3 in table
where t3.field = 1
select t3)
on t.parentID equals t2.ID into joined
from r in joined.DefaultIfEmpty() ...
另一种方法是像这样使用多个from
:
var query = from t in table
from t2 in table.Where(x => x.field = 1)
.Where(x => x.ID == t.parentID)
.DefaultIfEmpty()
select ....
关于entity-framework - Linq to SQL 自联接,其中联接的右侧部分被过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14345711/