作者:稀饭
在日常工作中,搭建一个SQL脚本,很容易涉及到多表join的过程,对于一些存在重复子查询的场景,可以将任务进行分割,利用with as语句将计算过程分拆,从而避免多次复用大表,产生不必要的时间消耗。
例如:
select a.*, b.*from (select * from table_1 where id in (select user_id from table_3 where dt = ‘2022-04-30’) aleft join(select * from table_2 where max(count_id) >= (select count(user_id) from table_3 where dt = ‘2022-04-30’) ) bon a.dt = b.dt
假设table_3是一个大表,在这段SQL中,需要复用table_3多次,且table_3表在查询逻辑中既有直接匹配也有基于聚合函数计算后进行匹配,所以无法很好的直接改写成join,那么为了减少对table_3大表的查询次数,可以基于with as语句,先将2022-04-30号的user_id查出来,再进行关联计算,从而减少整体SQL的耗时,并清晰化思路:
with table_step_1 -- 将table_3大表中2022-04-30号的数据取出来as(select user_id from table_3 where dt = ‘2022-04-30’), -- 注意格式中要写上英文逗号table_step_2 -- 将table_1和table_step_1进行匹配,避开了和table_3进行匹配as(select a.*from table_1 ajointable_step_1 bon a.id = b.user_id),table_step_3 -- 基于table_step_2、table_step_1 和table_2进行匹配,清晰化思路as(select b.*, c.*fromtable_step_2 bleft join(select * from table_step_3 where max(count_id) >= (select count(user_id) from table_step_1)) con b.dt = c.dt)select * from table_step_3 -- 最后对table_step_3进行查询展示;
with as就类似于一个视图或临时表,可以用来存储一部分的SQL语句作为别名,不同的是with as 属于一次性的,而且必须要和其他sql一起使用才可以。with as语句的最大的好处就是适当的提高代码可读性,而且如果with子句在后面要多次使用到,这可以大大的简化SQL;更重要的是:一次分析,多次使用,这也是为什么会提供性能的地方。
广告区↓

文章转载自稀饭居然不在家,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




