转载 

mysql专题系列三:mysql索引最左匹配原则理解以及常见的sql使用的索引情况的实测

分类:    277人阅读    IT小君  2023-08-24 17:21

「这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战

一、常见例子

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

sql
复制代码
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的最左索引匹配原则

转载于:https://juejin.cn/post/7055653180067020814?searchId=202308220930598DC660BCFDF8AB28608D

支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»