3

我是 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
4

1 回答 1

0

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

  1. 一般来说,尽量避免这么多的连接,而是将它们分解成几个小的查询。
  2. 不仅如此,您正在执行一个本身就是一项昂贵的操作的组,更不用说有这么多列了
  3. 我注意到您正在加入每个表中的所有列。尝试只选择相关的列。
  4. 还注意到,像alapl这样的组中没有使用很少的表。你需要它们吗?
  5. 对来自 EF 的只读数据使用 AsNoTracking()。这样你就可以加快速度。
  6. 使用 SQL 视图
于 2015-02-03T12:57:56.090 回答