美文网首页
【SQL】 sql 中 union 、or 、in 的效率问题

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

作者: miniy_7 | 来源:发表于2020-03-17 15:05 被阅读0次

结论(引用其他人的): 三个关键字不要轻信一种,结合实际情况分析
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 快

相关文章

网友评论

      本文标题:【SQL】 sql 中 union 、or 、in 的效率问题

      本文链接:https://www.haomeiwen.com/subject/emetyhtx.html