SQL查询性能(将一个查询拆分为更小的查询)

时间:2018-04-10 13:41:14

标签: sql performance teradata database-performance

我有一个SQL查询(在Teradata平台上运行)的功能 1)内部联接 2)where子句 3)分组

运行大约需要40分钟,我想让它更快。 (我没有权限为此表创建INDEX)。代码如下。我应该仅使用WHERE子句和另一个中间表来创建一个中间表W,以过滤掉与表X相交的W行,然后最终进行内连接吗?

    create table ABC as
    (select 
        b.acct_nb,
        max(b.lst_pmt) as pmt       
     from
     Y as b inner join X as a on 
     a.acct_nb = b.acct_nb
     where b.amount > 0
     group by b.acct_nb
     );

建议代码:

    create table W as
    select acct_nb,amount
    from Y
    where amount > 0;

    create table W2 as
    select a.acct_nb,b.amount
    from X as a inner join W as b
    on a.acct_nb = b.acct_nb;


    create table ABC as
    select a.acct_nb,max(b.lst_pmt) as pmt
    from W2 as a inner join Y as b
    on a.acct_nb = b.acct_nb
    group by b.acct_nb;

退出;

2 个答案:

答案 0 :(得分:0)

这是您的查询:

create table ABC as
    select b.acct_nb, max(b.lst_pmt) as pmt       
    from Y b inner join
         X a 
         on a.acct_nb = b.acct_nb
    where b.amount > 0
    group by b.acct_nb;

你并没有真正使用X(过滤除外),所以我想知道这是否符合你的要求:

create table ABC as
    select b.acct_nb, max(b.lst_pmt) as pmt       
    from Y b 
    where b.amount > 0
    group by b.acct_nb;

如果没有,您可以改为使用exists

create table ABC as
    select b.acct_nb, max(b.lst_pmt) as pmt       
    from Y b 
    where b.amount > 0
          exists (select 1 from X a where a.acct_nb = b.acct_nb)
    group by b.acct_nb;

我会在使用临时表之前尝试这些方法。

答案 1 :(得分:0)

建议的代码可能无法提高性能。

没有解释或查询日志信息很难提供建议,但您可能会尝试在加入之前进行汇总:

select b.*
from 
 (
   select 
      acct_nb,
      max(lst_pmt) as pmt       
   from Y
   where amount > 0
   group by b.acct_nb
 ) as b 
inner join X as a 
on a.acct_nb = b.acct_nb