MySQL中or、in、union与索引优化详析

作者:58沈剑 时间:2024-01-18 08:21:55 

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

假设订单业务表结构为:


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可读性差,可理解性差,可维护性差,强烈不推荐

六、作业

这样的查询能够命中索引么?


select * from order where uid in (

select uid from order where status=0

)

select * from order where status in (0, 1) order by date desc

select * from order where status=0 or date <= CURDATE()

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

来源:https://mp.weixin.qq.com/s/ZWez27EmVw_u7GzNbvXuYw

标签:mysql,or,索引
0
投稿

猜你喜欢

  • 在双python下设置python3为默认的方法

    2022-03-02 10:31:39
  • 使用BULK INSERT大批量导入数据 SQLSERVER

    2012-01-05 19:26:36
  • python实现播放音频和录音功能示例代码

    2023-08-20 23:23:15
  • Python 实现打印单词的菱形字符图案

    2021-06-30 20:08:52
  • MYSQL的binary解决mysql数据大小写敏感问题的方法

    2024-01-25 16:38:26
  • python迭代器的使用方法实例

    2022-03-16 18:00:09
  • python实现异常信息堆栈输出到日志文件

    2022-04-26 20:26:21
  • Django框架视图介绍与使用详解

    2021-03-29 08:50:46
  • 解决PyCharm 中写 Turtle代码没提示以及标黄的问题

    2023-05-12 09:08:30
  • python 基于pygame实现俄罗斯方块

    2021-07-22 15:47:23
  • Python requests接口测试实现代码

    2023-09-10 18:09:21
  • Python神经网络TensorFlow基于CNN卷积识别手写数字

    2022-06-18 20:23:00
  • Python知识点详解之正则表达式语法

    2022-02-08 17:01:31
  • ASP中取得图片宽度和高度

    2009-11-08 18:39:00
  • Pycharm学习教程(3) 代码运行调试

    2023-04-11 00:01:18
  • asp如何在页面中实现对电子信箱的访问?

    2010-06-26 12:34:00
  • 解密ThinkPHP3.1.2版本之独立分组功能应用

    2023-11-20 09:06:02
  • 让IE8支持eWebEditor在线编辑器

    2010-02-28 10:36:00
  • 将Reporting services的RDL文件拷贝到另外一台机器时报Data at the root level is invalid的解决方法

    2012-07-11 15:33:45
  • Python实现简单猜拳游戏

    2022-07-08 04:40:10
  • asp之家 网络编程 m.aspxhome.com