调整 SQL 查询:在同一 table 上使用聚合函数的子查询

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

以下查询大约需要 30 秒才能给出结果。 table1 包含 ~20m 行 表 2 包含 ~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) -- 加入

备注:

  • Table 别名应该有意义。 t3 对于 table2 是认知上的不协调,即使我知道这些是虚构的名字。
  • not exists(尤其是正确的索引)应该比聚合子查询更快。
  • 索引将满足where子句,减少过滤所需的数据。
  • select distinct 是一个语句。 distinct 不是一个函数,所以括号什么都不做。
  • 从不FROM 子句中使用逗号。 始终使用正确、明确、标准的JOIN语法。