此文为了确定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博客
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。