此文为了确定MySQL联合索引的覆盖问题。

首先联合索引是建立在「最左前缀」原则之上。

其次select字段也需要被索引覆盖,否则会进行回表查询。

测试准备

MySQL 版本 8.0.32-arm64版本,InnoDB引擎。

创建一张表名test_index,有 a、b、c、d、e 共5个字段。其中a、b、c、d 4个字段按顺序组成的联合索引,索引名称为idx_abcd。e为非索引字段。


explain select * from test_index where a = 1;(覆盖a)

explain select * from test_index where a = 1 and b = 1;(覆盖a、b)

结果:type=ref, key = idx_abcd, Extra = null

where条件覆盖索引前导列,但select字段被索引覆盖


explain select a,b,d from test_index where a = 1;(覆盖a)

explain select a,b,c from test_index where a = 1 and b = 1;(覆盖a、b)

结果:type=ref, key = idx_abcd, Extra = Using index

覆盖索引前导列,并且select字段被索引覆盖


explain select * from test_index where b = 1;

explain select * from test_index where b = 1 and d = 1;

结果:type=ALL,key = NULL,Extra=Using where

未覆盖索引,全表扫描


explain select * from test_index where a = 1 and c = 1; (覆盖a)

explain select * from test_index where a = 1 and b = 1 and c > 1 and d = 1;(覆盖a、b、c)

结果: type=ref,key = idx_abcd, Extra=Using index condition

覆盖索引前导列,查询列未被索引覆盖(Using index condition)


explain select a,b,c from test_index where a = 1 and c = 1; (覆盖a)

explain select a,b,c from test_index where a = 1 and b = 1 and c > 1 and d = 1; (覆盖a、b、c)

结果:type=ref,key = idx_abcd, Extra=Using where; Using index

覆盖索引前导列,查询的列被索引覆盖(Using index)

ps:范围查询也可以覆盖索引


参考内容:MySQL-explain-extra字段详解_explain extra null_冰柠加糖的博客-CSDN博客


我有切糕
863 声望45 粉丝

Java架构师,技术经理