MySQL的or/in/union与索引优化

转载自:MySQL的or/in/union与索引优化 https://blog.csdn.net/zhangweiwei2020/article/details/80005590html

假设订单业务表结构为:程序员

order(oid, date, uid, status, money, time, …)post

其中:优化

  • oid,订单ID主键ui

  • date,下单日期,有普通索引,管理后台常常按照date查询spa

  • uid,用户ID,有普通索引,用户查询本身订单.net

  • status,订单状态,有普通索引,管理后台常常按照status查询code

  • money/time,订单金额/时间,被查询字段,无索引htm

--假设订单有三种状态:0已下单,1已支付,2已完成

--如下查询未完成的订单,哪一个SQL更快呢?
--方案1
    select * from order where status!=2
--方案2
    select * from order where status=0 or status=1
--方案3
    select * from order where status IN (0,1)
--方案4
    select * from order where status=0
    union all
    select * from order where status=1

--结论:方案1最慢,方案2,3,4都能命中索引

一:union all 确定是可以命中索引的blog

--方案4
select * from order where status=0
union all
select * from order where status=1

说明:

  • 直接告诉MySQL怎么作,MySQL耗费的CPU最少

  • 程序员并不常常这么写SQL(union all)

二:简单的in可以命中索引

--方案3
select * from order where status in (0,1)

说明:

  • MySQL思考,查询优化耗费的cpuunion all多,但能够忽略不计

  • 程序员最常这么写SQL(in),这个例子,最建议这么写

三:对于or,新版的MySQL可以命中索引

--方案2
select * from order where status=0 or status=1

说明:

  • MySQL思考,查询优化耗费的cpuin多,别把负担交给MySQL

  • 不建议程序员频繁用or,不是全部的or都命中索引

  • 对于老版本的MySQL,建议查询分析下

4、对于!=,负向查询确定不能命中索引

--方案1
select * from order where status!=2

说明:

  • 全表扫描,效率最低全部方案中最慢

  • 禁止使用负向查询

5、其余方案

--其余
select * from order where status < 2

这个具体的例子中,确实快,可是:

  • 这个例子只举了3个状态,实际业务不止这3个状态,而且状态的“值”正好知足偏序关系,万一是查其余状态呢,SQL不宜依赖于枚举的值,方案不通用

  • 这个SQL可读性差,可理解性差,可维护性差,强烈不推荐

相关文章
相关标签/搜索