【问题标题】:SQL self join query to LINQ querySQL 自联接查询到 LINQ 查询
【发布时间】:2013-11-09 21:14:12
【问题描述】:

我对将 SQL 查询转换为 LINQ 感到困惑。任何机构都可以帮助我。 这是我的查询

SELECT x.*
  FROM FilterType x
  JOIN (SELECT t.FilterType
          FROM FilterType t
          where FilterId in (7,15)
      GROUP BY t.FilterType
        HAVING COUNT(t.FilterType) > 1) y ON y.FilterType = x.FilterType

提前致谢。

【问题讨论】:

  • 您可以使用 LINQPad 将 SQL 查询转换为 LINQ。
  • @JibranKhan 我相信 LINQPad 会做相反的事情 - 它显示为 LINQ 查询生成的 SQL。要生成 LINQ,您需要 Linqer 之类的东西
  • 然后,还有一个叫 Linqer,但请在此处查看答案stackoverflow.com/questions/12238423/…

标签: c# sql linq


【解决方案1】:

假设你有int[] ids = { 7, 15 }。然后查询将如下所示:

from t in FilterType.Where(x => ids.Contains(x.FilterId))
group t by t.FilterType into g
where g.Count() > 1
from f in g
select f

或者用方法语法:

FilterType.Where(x => ids.Contains(x.FilterId))
          .GroupBy(t => t.FilterType)
          .Where(g => g.Count() > 1)
          .SelectMany(g => g);

生成的 SQL 不会和你的完全一样,但结果应该是一样的。

【讨论】:

    【解决方案2】:
    from a in FilterType
    join b in
        (
            from x in FilterType
            where (new int[]{7, 15}).Contains(x.FilterID)
            group x by new {x.FilterType} into g
            where g.Count() > 1
            select new {FilterType = g.Key.FilterType}
        ) on a.FilterType equals b.FilterType
    select a;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多