sql优化策略——不必要的union

    不必要的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;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值