【SQL】 sql 中 union 、or 、in 的效率问题

结论(引用其他人的): 三个关键字不要轻信一种,结合实际情况分析
1.对于索引列来最好使用union all,因复杂的查询【包含运算等】将使or、in放弃索引而全表扫描,除非你能确定or、in会使用索引
2.对于只有非索引字段来说你就老老实实的用or 或者in,因为 非索引字段本来要全表扫描而union all 只成倍增加表扫描的次数
3.对于及有索引字段【索引字段有效】又包含非索引字段来时,按理你也使用or 、in或者union all 都可以

举例大数据量表
# 使用 or 方式连接
SELECT
    us.alias 
FROM
    user us
    LEFT JOIN dept_user du ON us.user_id = du.user_id
    LEFT JOIN user_work uw ON us.user_id = uw.user_id
    where 1 =1 
    and (us.base_sex = '男')
    and (du.date_end is null and du.date_begin >= '2016-03-17' and du.job_duty_level in ('正厅级', '副厅级'))
    or (uw.date_begin >= '2019-03-17' and uw.duty_level in ('正厅级', '副厅级'))
# 使用 union 方式连接
SELECT
    us.alias 
FROM
    user us
    LEFT JOIN dept_user du ON us.user_id = du.user_id
    where 1 =1 
    and (us.base_sex = '男')
    and (du.date_end is null and du.date_begin >= '2016-03-17' and du.job_duty_level in ('正厅级', '副厅级'))
union 
SELECT
    us.alias 
FROM
    user us
    LEFT JOIN user_work uw ON us.user_id = uw.user_id
    where 1 =1 
    and (us.base_sex = '男')
    and (uw.date_begin >= '2019-03-17' and uw.duty_level in ('正厅级', '副厅级'))

上诉中: 使用union 要比 or 快

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT从业者的职业生涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值