SQL索引优化2(MySQL的or/in/union与索引优化)
2017-08-01 14:41
726 查看
问题
假设订单业务表结构为: order(oid, date, uid, status, money, time, …) 其中: oid,订单ID,主键 date,下单日期,有普通索引,管理后台经常按照date查询 uid,用户ID,有普通索引,用户查询自己订单 status,订单状态,有普通索引,管理后台经常按照status查询 money/time,订单金额/时间,被查询字段,无索引 … 假设订单有三种状态:0已下单,1已支付,2已完成 业务需求,查询未完成的订单,哪个SQL更快呢? select * from order where status!=2 select * from order where status=0 or status=1 select * from order where status IN (0,1) select * from order where status=0 union all select * from order where status=1
结论
方案1最慢,方案2,3,4都能命中索引
解析
一:union all 肯定是能够命中索引的
select * from order where status=0 union all select * from order where status=1 说明: 直接告诉MySQL怎么做,MySQL耗费的CPU最少 程序员并不经常这么写SQL(union all)
二:简单的in能够命中索引
select * from order where status in (0,1) 说明: 让MySQL思考,查询优化耗费的cpu比union all多,但可以忽略不计 程序员最常这么写SQL(in),这个例子,最建议这么写
三:对于or,新版的MySQL能够命中索引
select * from order where status=0 or status=1 说明: 让MySQL思考,查询优化耗费的cpu比in多,别把负担交给MySQL 不建议程序员频繁用or,不是所有的or都命中索引 对于老版本的MySQL,建议查询分析下
四、对于!=,负向查询肯定不能命中索引(特别注意!!!!!!)
select * from order where status!=2 说明: 全表扫描,效率最低,所有方案中最慢 禁止使用负向查询
五、其他方案
select * from order where status < 2 这个具体的例子中,确实快,但是: 这个例子只举了3个状态,实际业务不止这3个状态,并且状态的“值”正好满足偏序关系,万一是查其他状态呢,SQL不宜依赖于枚举的值,方案不通用 这个SQL可读性差,可理解性差,可维护性差,强烈不推荐
相关文章推荐
- sql优化之:数据库索引创建原则,or/in/union与索引优化,聚集索引/非聚集索引/联合索引/索引覆盖,MySQL冗余数据的三种方案,MySQL双主一致性架构优化(来源:架构师之路)
- MySQL的or/in/union与索引优化
- 170505、MySQL的or/in/union与索引优化
- MySQL的or/in/union与索引优化
- MySQL的or/in/union与索引优化
- MySQL的or/in/union与索引优化
- 【SQL优化】B树索引位图转换及OR到UNION(ALL)的改写
- 1、Mysql:mysql简单的索引和in、or、union unionall语句查询速度
- mysql通过将or改成union来优化sql性能问题一例
- MYSQL索引优化: IN 和 OR 替换为 union all
- sql查询优化经验(mysql索引优化注意)
- mysql 实战 or、in与union all 的查询效率
- MySQL5.6 单列、多列索引以及IN语句的优化(翻译)
- MySQL索引的数据结构与常用SQL优化
- UNION or OR in SQL Server Queries
- MySQL索引优化分析,SQL优化,慢查询分析
- mysql sql优化和索引摘录
- Importing/Indexing database (MySQL or SQL Server) in Solr using Data Import Handler--转载
- Mysql-索引-BTree类型 ” 的sql优化
- 【MySQL】基于MySQL的SQL优化(五)——建立索引优化SQL