此文为了确定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博客