暂无图片
周伟
2023-03-31
关于笛卡尔积的优化改写

各位专家,

我这里有个关于笛卡尔积的SQL,SQL是举的一个例子,原SQL和这种情形是一样的:

select t1.id, ti.code,t2.name,

     -sum(case when t1.id = t2.before_id then t2.before_price

                     when t1.id = t2.after_id then t2.after_price)/1000 as true_price

from t1, t2

group by

t1.id, t2.name;

这个SQL里面,t1表里面有大约500万行,t2表大约有10000行,因为 t1 和 t2表在 from 后面没有加任何的where 连接条件,导致CBO先将它们做了笛卡尔积,然后再走case语句计算,这样的话性能就耗在了笛卡尔积的地方。

各位专家,有没有什么思路可以对这个SQL进行改写,以便消除笛卡尔积的?


收藏
3条回答
默认
最新
周伟

更正一下SQL,忘了写else end了:

select t1.id, ti.code,t2.name,

     -sum(case when t1.id = t2.before_id then t2.before_price

                     when t1.id = t2.after_id then t2.after_price

                     esle 0

                     end)/1000 as true_price

from t1, t2

group by

t1.id, t2.name;

暂无图片 评论
暂无图片 有用 0
chengang

做了一下测试。应该是等价改写的

with t1 as ( select 1 as id,'张飞' as name union all select 2,'刘备' union all select 3,'华佗' union all select 5,'华雄' union all select 6,'郭嘉' ) ,t2 as ( select 1 as before\_id,2 as after\_id,100 as before\_price,200 as after\_price union all select 3 as beforeid, 3 as after\_id,300 as before\_price,400 as after\_price ) select id, name, sum(sum\_price) from( select t1.id, t1.name, sum(t2.before\_price) as sum\_price from t1 inner join t2 on t1.id = t2.before\_id group by t1.id, t1.name union all select t1.id, t1.name,sum(t2.after\_price) sum\_price from t1 inner join t2 on t1.id = t2.after\_id where t2.before\_id <> t2.after\_id group by t1.id, t1.name )as t group by id, name
暂无图片 评论
暂无图片 有用 0
周伟
问题已关闭: 问题已经得到解决
暂无图片 评论
暂无图片 有用 0
回答交流
提交
问题信息
请登录之后查看
邀请回答
暂无人订阅该标签,敬请期待~~
暂无图片墨值悬赏