不必要的union(分析sql逻辑),相似的子查询重复union,仅仅为了过滤不同的条件。
影响:表重复冗余扫描多次,执行效率低
优化方法:使用case when改写union
拓展说明:union与union all的区别
union:对两个结果集进行并集操作,重复行只保留一条,同时进行默认规则的排序
union all:对两个结果集进行并集操作,相当于结果集拼接,包括重复行,不进行排序
举例:
select id,score,'type1' from table_b where type=1
union select id,score,'type2' from table_b where type=2
union select id,score,'type3' from table_b where type=3;
-- 可以优化为下面写法
select
id,
score,
case type when 1 then 'type1'
when 2 then 'type2'
when 3 then 'type3' end as type
from table_b;
-- 等价于
select
id,
score,
case when type=1 then 'type1'
when type=2 then 'type2'
when type=3 then 'type3' end as type
from table_b;