文档首页/ 数据仓库服务 GaussDB(DWS)/ 性能调优/ 实际调优案例/ 案例:改写SQL消除子查询(案例1)
更新时间:2024-07-01 GMT+08:00
分享

案例:改写SQL消除子查询(案例1)

现象描述

1
2
3
4
select 
    1,
    (select count(*) from customer_address_001 a4 where a4.ca_address_sk = a.ca_address_sk) as GZCS 
from customer_address_001 a;

此SQL性能较差,查看发现执行计划中存在SubPlan,引用SubPlan结果的算子可能需要反复的调用获取这个SubPlan的值,即SubPlan以下的结果要重复执行很多次。具体如下:

优化说明

此优化的核心就是消除子查询。那么从SQL语义出发,可以等价改写SQL为:

1
2
3
4
5
6
select 
    1, 
    coalesce(a4.c1, 0)
from
    (select count(*) c1, a4.ca_address_sk from customer_address_001 a4 group by a4.ca_address_sk) a4
right join customer_address_001 a on a4.ca_address_sk = a.ca_address_sk;

相关文档