【问题标题】:How to write a join with "not equal" in LINQ to SQL?如何在 LINQ to SQL 中编写“不等于”连接?
【发布时间】:2015-04-08 00:21:28
【问题描述】:

我有一张表employees,其中包含以下列

ID, Name, ..., RelatedID, ...

我想在 LINQ to SQL 中编写以下选择:

select distinct b.ID, b.Name
from employees b
join employees a on a.RelatedID > 0
where b.id = a.RelatedID

我认为表达式a.RelatedID > 0 基本上是0 not equals a.RelatedID,但不支持语法。

任何想法如何实现我的目标?

:编辑

我找到了解决方案,请参阅我发布的答案。

【问题讨论】:

  • 这是X Y problem。与其告诉我们您要解决的任何问题的解决方案并要求我们使其发挥作用,不如告诉我们您要解决的问题并要求我们提供解决方案。这个 Linq 语句应该完成什么?
  • 请记住,任何内部联接都可以写成带有 where 子句中的 on 条件的交叉联接。
  • 那么你是在写 linq 语句还是 SQL 语句,我不确定你想提供什么答案:)
  • @juharr 您将如何编写带有交叉连接的查询?我试过from b in employees from a in employees where a.RelatedID > 0 && b.ID == a.RelatedID select b,但它没有给出正确的结果(返回的记录太多)

标签: c# join linq-to-sql equals


【解决方案1】:

只需将您的where 与您的加入过滤器交换即可。您已将您的实际加入过滤器放入您的 Where 并将您的过滤作为您的加入条件,因此您的问题。

var query = from b in employees
    join a in employees on b.id equals a.RelatedID
    where b.RelatedID > 0
    select ...;

请注意,您可能还希望在加入之前进行过滤(不确定这在 SQL 中是否重要;在 LINQ to objects 中肯定会有所帮助)

var query = from b in employees
    where b.RelatedID > 0
    join a in employees on b.id equals a.RelatedID
    select ...;

【讨论】:

    【解决方案2】:

    我自己找到了一个解决方案,看起来很丑,但它确实有效:

    from b in employees  
    where (from a in employees where a.RelatedID > 0 select a.RelatedID).Contains(b.ID)
    select b;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2015-06-20
      相关资源
      最近更新 更多