首页 > 解决方案 > 如何使用 with 语句加速慢速左连接 SQL 查询?

问题描述

我有一个位于多列的左连接查询(在雪花中)。X有 1100 万行和Y1 亿行。它非常慢(大约 25 分钟),每天需要运行很多次。有没有可能使用 with 语句(或任何其他方法)来加速它?这是查询:

select id, start_ts, start_ts_lgn from
(select id, start_ts 
    from X
    where start_ts >= '2019-11-01')a
left join
(select id as id_frm_lgn, cast(cast(strt_dt as varchar(10))||' '||cast(strt_tm as varchar(12)) as timestamp) as start_ts_lgn
    from Y
    where strt_dt >= '2019-10-01')b
on a.id = b.id_frm_lgn
and a.start_ts > b.start_ts_lgn;

标签: sqlquery-optimization

解决方案


要加快此查询,您可以添加索引:

create index ix1 on X (start_ts, id);

create index ix2 on Y (strt_dt, id);

推荐阅读