SQL 查询性能(是否将一个查询分解成更小的查询)
SQL Query performance (break-up one query into smaller ones or not)
我有一个 SQL 查询(运行 在 Teradata 平台上)具有以下特点
1)内部连接
2) where子句
3) 分组依据
运行 大约需要 40 分钟,我想让它更快。 (我没有为此 table 创建索引的权限)。代码如下。我是否应该仅使用 WHERE 子句和另一个中间 table 来创建一个中间 table W 来过滤掉与 table 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;
退出;
这是您的查询:
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;
我会在使用临时 table 之前尝试这些方法。
提议的代码可能不会提高性能。
如果没有 Explain 或 QueryLog 信息,很难给出建议,但您可以尝试在加入之前进行聚合:
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
我有一个 SQL 查询(运行 在 Teradata 平台上)具有以下特点 1)内部连接 2) where子句 3) 分组依据
运行 大约需要 40 分钟,我想让它更快。 (我没有为此 table 创建索引的权限)。代码如下。我是否应该仅使用 WHERE 子句和另一个中间 table 来创建一个中间 table W 来过滤掉与 table 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;
退出;
这是您的查询:
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;
我会在使用临时 table 之前尝试这些方法。
提议的代码可能不会提高性能。
如果没有 Explain 或 QueryLog 信息,很难给出建议,但您可以尝试在加入之前进行聚合:
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