簡體   English   中英

調優SQL查詢:在同一表上具有聚合功能的子查詢

[英]Tuning SQL query : subquery with aggregate function on the same table

以下查詢大約需要30秒才能得出結果。 table1包含〜20m行table2包含〜10000行

我正在嘗試找到一種提高性能的方法。 有任何想法嗎 ?

declare @PreviousMonthDate datetime 
select @PreviousMonthDate = (SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101') as [PreviousMonthDate])

     select  
 distinct(t1.code), t1.ent, t3.lib, t3.typ from table1 t1, table2 t3
     where (select min(t2.dat) from table1 t2 where   t2.code=t1.code) >@PreviousMonthDate
and t1.ent in ('XXX')
and t1.code=t3.cod
and t1.dat>@PreviousMonthDate

謝謝

這是您的查詢,更合理地寫為:

 select t1.code, t1.ent, t2.lib, t2.typ
 from table1 t1 join
      table2 t2
      on t1.code = t2.cod
 where not exists (select 1
                   from table1 tt1
                   where tt1.code = t1.code and
                         tt1.dat <= @PreviousMonthDate 
                  ) and
       t1.ent = 'XXX' and 
       t1.dat > @PreviousMonthDate;

對於此查詢,您需要以下索引:

  • table1(ent, dat, code) -哪里
  • table1(code, dat) -用於子查詢
  • table2(cod, lib, typ) -用於聯接

筆記:

  • 表別名應該有意義。 table2 t3在認知上是不和諧的,即使我知道這些都是虛構的名字。
  • not exists (尤其是具有正確索引的索引)應該比聚合子查詢快。
  • 索引將滿足where子句,從而減少了過濾所需的數據。
  • select distinct是一個聲明。 distinct不是函數,因此括號不起作用。
  • 請勿FROM子句中使用逗號。 始終使用正確,明確,標准的JOIN語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM