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