多个连接LINQ查询性能

时间:2012-08-20 19:34:53

标签: performance linq

我是LINQ的新手并且知之甚少。 我有以下复杂的查询。它运行速度比我翻译成LINQ的存储过程慢3到4倍。

让我更快跑的任何提示?

var result = from a in db.A 
    join al in db.AL.Where(q => q.CurrentLocation == 1) on a.AID equals al.AID into tmp_al
    from al in tmp_al.DefaultIfEmpty()
    join l in db.Lon al.LID equals l.LID into tmp_l
    from l in tmp_l.DefaultIfEmpty()
    join r in db.R on l.RID equals r.RID into tmp_r
    from r in tmp_r.DefaultIfEmpty()
    join b in db.B on r.BID equals b.BID into tmp_b
    from b in tmp_b.DefaultIfEmpty()
    join ap in db.AP.Where(q => q.CurrentProtocol == 1) on a.AID equals ap.AID into tmp_ap
    from ap in tmp_ap.DefaultIfEmpty()
    join p in db.P on ap.PID equals p.PID into tmp_p
    from p in tmp_p.DefaultIfEmpty()
    join s in db.S on a.SID equals s.SID into tmp_s
    from s in tmp_s.DefaultIfEmpty()
    join ans in db.AS on a.ASID equals ans.ASID into tmp_ans
    from ans in tmp_ans.DefaultIfEmpty()
    join pr in db.P on p.PI equals pr.PID into tmp_pr
    from pr in tmp_pr.DefaultIfEmpty()
    where a.Active == 1
    group a by new { a.Active, pr.LN, pr.FN, b.BN, r.RID, r.R1, p.PN, s.S1, ans.AS1 }
      into grp
      orderby grp.Key.BN, grp.Key.R1, grp.Key.PN, grp.Key.S1, grp.Key.AS1
      select new
      {
          PIName = grp.Key.LN + " " + grp.Key.FN,
          BN = grp.Key.BN,
          RID = grp.Key.RID,
          R = grp.Key.R1,
          PN = grp.Key.PN,
          S = grp.Key.S1,
          AS = grp.Key.AS1,
          NumberOA = grp.Count()
      };

感谢您的回答。 @Albin Sunnanbo:我不知道如何检查执行计划。我的LINQ正确运行并产生所需的输出。它只是很慢。我想发言。 @usr:原来的sql如下:  抱歉傻桌名。原始代码是保密的。所以我不会发布完整的表名。

CREATE PROCEDURE [dbo].[report_CBRP] --  
AS
SELECT LN + ' ' + FN As PIN, BN, R.RID, R, PN, 
S, AS, COUNT(*) As NOA 
FROM A 
LEFT JOIN AL 
ON A.AID = AL.AID 
AND AL.CL = 1
LEFT JOIN L 
ON AL.LID = L.LID 
LEFT JOIN R
ON L.RID = R.RID 
LEFT JOIN B 
ON R.BID = B.BID 
LEFT JOIN AP
ON A.AID = AP.AID 
AND AP.CPl = 1
LEFT JOIN P 
ON AP.PID = P.PID 
LEFT JOIN S 
ON A.SID = S.SID 
LEFT JOIN AS
ON A.ASID = AS.ASID
LEFT JOIN P
ON P.PI = P.PID 
GROUP BY A.A, LN , FN , B.BN, R.RID, R.R, P.PN, 
S.S, AS.AS 
HAVING A.A = 1 
ORDER BY B.BN, R.R, P.PN, S, AS
GO

1 个答案:

答案 0 :(得分:0)

看来你在这里做了SQL艰苦的生活。

  1. 一般来说,尽量避免这么多连接,而是将它们分成几个小查询。
  2. 更重要的是,你正在执行一个组,本身就是一个昂贵的操作,更不用说有这么多列了
  3. 我注意到您正在加入所有每个表中的列。尝试仅选择相关列。
  4. 还注意到, al ap l 等组中没有使用这些表。你需要它们吗?
  5. 使用AsNoTracking()获取EF的只读数据。通过这种方式,你可以加快速度。
  6. 使用SQL视图