mysql索引最左匹配原则理解以及常见的sql使用的索引情况的实测

本文详细解析了MySQL中复合索引(联合索引)的最左匹配原则,通过多个实例展示了如何利用这一特性来优化查询效率。文章强调了在查询条件中,确保索引的最左侧字段被使用的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、常见例子

mysql索引最左匹配原则主要是针对复合索引(联合索引)来说的,比如你在字段 a,b,c 建立了一个联合索引 index_abc

ALTER TABLE `test` 
ADD INDEX `index_abc`(`a`,`b`, `c`) USING BTREE;
  1. explain select * from test where a<10 ; # 用索引
    在这里插入图片描述

  2. explain select * from test where a<10 and b <10; # 用索引
    在这里插入图片描述

  3. explain select * from test where a<10 and b <10 and c<10; # 用索引

在这里插入图片描述
能不能将 a,b出现顺序换一下,a,b,c出现顺序换一下

  1. explain select * from test where b<10 and a <10; # 用索引

在这里插入图片描述
5. explain select * from test where b<10 and a <10 and c<10; # 用索引

在这里插入图片描述

  1. explain select * from test where b<10 and c <10;# 用不到索引

在这里插入图片描述

  1. explain select * from test where a<10 and c <10; # a 能用到索引, c用不到
    在这里插入图片描述

  2. explain select * from test where a=1001 #用到索引
    在这里插入图片描述

  3. explain select * from test where a=1001 and b=1002 #用到索引
    在这里插入图片描述

  4. explain select * from test where b=1002 and a=1001 # 用到索引,mysql 优化器会将 sql优化成:explain select * from test where a=1001 and b=1002

在这里插入图片描述

  1. explain select * from test where a=1001 and c=1003 # a 能用到索引,c用不到
    在这里插入图片描述
  2. explain select * from test where c=1003 # 用不到索引
    在这里插入图片描述
  3. explain select * from test where b=1002 # 用不到索引
    在这里插入图片描述

二、总结

如果有复合索引 index_abc(a,b,c),且是select * 则

  1. 只要保证 a 字段能够出现在where条件后,不论 a 出现的先后顺序,就一定能用索引 (适用于查询条件是 “=” )
  2. a 是查询条件的第一个条件则一定能用索引(适用于查询条件是 “=”,"<" , “>”)
  3. 查询条件只有 b 或 c 或 b c 则不能使用索引

一般在面试的时候查询条件是“=” 且前边都是select * 如果不是这样则上边的结论不成立

三、参考链接

mysql索引最左匹配原则的理解
EXPLAIN 命令详解
mysql的最左索引匹配原则

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T-OPEN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值