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

开发 开发工具
本文是关于MySQL的or/in/union与索引优化的一分钟系列文章。

本文缘起自《一分钟了解索引技巧》的作业题。

假设订单业务表结构为:

  1. order(oid, date, uid, status, money, time, …) 

其中:

  • oid,订单ID,主键
  • date,下单日期,有普通索引,管理后台经常按照date查询
  • uid,用户ID,有普通索引,用户查询自己订单
  • status,订单状态,有普通索引,管理后台经常按照status查询
  • money/time,订单金额/时间,被查询字段,无索引

假设订单有三种状态: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 
  5. union all 
  6. select * from order where status=1 

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

但是...

MySQL

一:union all 肯定是能够***索引的

  1. select * from order where status=0 
  2. union all 
  3. select * from order where status=1 

说明:

  • 直接告诉MySQL怎么做,MySQL耗费的CPU最少
  • 程序员并不经常这么写SQL(union all)

二:简单的in能够***索引

  1. select * from order where status in (0,1) 

说明:

  • 让MySQL思考,查询优化耗费的cpu比union all多,但可以忽略不计
  • 程序员最常这么写SQL(in),这个例子,最建议这么写

三:对于or,新版的MySQL能够***索引

  1. select * from order where status=0 or status=1 

说明:

  • 让MySQL思考,查询优化耗费的cpu比in多,别把负担交给MySQL
  • 不建议程序员频繁用or,不是所有的or都***索引
  • 对于老版本的MySQL,建议查询分析下

四、对于!=,负向查询肯定不能***索引

  1. select * from order where status!=2 

说明:

  • 全表扫描,效率***,所有方案中最慢
  • 禁止使用负向查询

五、其他方案

  1. select * from order where status < 2 

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

  • 这个例子只举了3个状态,实际业务不止这3个状态,并且状态的“值”正好满足偏序关系,万一是查其他状态呢,SQL不宜依赖于枚举的值,方案不通用
  • 这个SQL可读性差,可理解性差,可维护性差,强烈不推荐

六、作业

这样的查询能够***索引么?

  1. select * from order where uid in ( 
  2.          select uid from order where status=0 
  3. select * from order where status in (0, 1) order by date desc 
  4. select * from order where status=0 or date <= CURDATE() 

注:此为示例,别较真SQL对应业务的合理性。

【本文为51CTO专栏作者“58沈剑”原创稿件,转载请联系原作者】

戳这里,看该作者更多好文

责任编辑:赵宁宁 来源: 51CTO专栏
相关推荐

2011-06-08 15:08:38

MySQLWhere优化

2020-10-19 19:45:58

MySQL数据库优化

2010-06-04 11:28:05

MySQL数据库

2018-06-07 08:54:01

MySQL性能优化索引

2010-05-12 11:14:25

MySQL SQL优化

2010-10-12 16:44:36

MySQL语句

2018-04-09 14:25:06

数据库MySQL索引

2010-05-14 17:56:16

SQL优化索引

2010-10-08 16:20:35

MySQL语句

2020-05-20 18:40:11

MySQL回表与索引数据库

2017-09-05 12:44:15

MySQLSQL优化覆盖索引

2010-05-21 12:15:52

2021-11-09 07:59:50

开发

2010-10-12 14:53:31

mysql索引优化

2023-11-01 09:44:21

MySQLJava

2010-05-27 16:12:10

MySQL索引

2011-07-11 15:28:19

MySQL索引优化

2020-02-14 18:10:40

MySQL索引数据库

2010-05-26 13:42:08

MySQL数据库索引

2011-10-13 09:44:49

MySQL
点赞
收藏

51CTO技术栈公众号