转换相关并将SQL查询连接到LINQ

时间:2014-05-03 05:31:32

标签: c# sql-server linq tsql sql-to-linq-conversion

请考虑此查询:

SELECT DISTINCT(fld_09 + fld_10), fld_Switch, fld_Area
FROM   Mytbl t
WHERE  fld_Year = 2000
   AND fld_Month = 1
   AND fld_02 != '04'
   AND fld_Switch = 2
   AND (
           (fld_09 + fld_10) NOT IN 
                (SELECT DISTINCT(fld_09 + fld_10)
                 FROM  Mytbl q
                 WHERE  fld_Year = 2000
                 AND fld_Month = 1
                 AND fld_02 != '04'
                 AND fld_Switch = 1
                 AND t.fld_Area = q.fld_Area)
       )
GROUP BY fld_Area, fld_09, fld_10, fld_Switch

这个查询在1秒内​​执行。我想用linq编写这个查询。我写了这段代码:

var subQuery= (from r in ent.Mytbl 
               where r.fld_Year == Year &&
                     r.fld_Month == Month &&
                     r.fld_Switch == 1 &&
                     r.fld_02 != "04"
               select r.fld_09 + r.fld_10;

var query = (from o in ent.Mytbl 
             let code = o.fld_09 + o.fld_10
             where o.fld_Year == Year &&
                   o.fld_Month == Month &&
                   o.fld_Switch == 2 &&
                   o.fld_F02 != "04" &&
                   subQuery.Contains(code) == false
             group o by new { o.fld_Area, o.fld_09, o.fld_10, o.fld_Switch }
             into gr
             select new
             {
                 a = gr.Key.fld_09 + gr.Key.fld_10,
                 gr.Key.fld_Area,c=gr.Count()
             }).Distinct();

这2个查询是否相等?

执行时第二次查询需要2分钟。我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

如果您还没有,请务必使用LinqPad来调整此查询。我相信let条款是你的表现。