为什么Mysql 在覆盖索引下的like ‘%xxx%’查询能使用到索引,原理是什么?
下面是在mysql5.7的一个示例:
第一步准备数据
CREATE TABLE `Student` (
`ID` int(11) NOT NULL primary key AUTO_INCREMENT,
`Name` varchar(4) NOT NULL DEFAULT '' COMMENT '姓名',
`Age` int(5) NOT NULL DEFAULT '0' COMMENT '年龄',
`Email` varchar(10) NOT NULL DEFAULT '' COMMENT '邮箱'
) ENGINE=InnoDB ;
insert into Student(name,age,email) values ("aa",11,"qq@qq.com"),("bb",22,"qq@qq.com"),("cc",22,"qq@qq.com")
第二步查询分析,未加索引。
explain select name,age from Student where name like "%b%"
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE Student NULL ALL NULL NULL NULL NULL 3 33.33 Using where; Using filesort
文件排序,全局扫描。
第三步创建复合索引(name,age)
alter table Student add INDEX index_nameAge (name,age)
第四步查询分析,覆盖索引。
explain select name,age from Student where name like "%b%"
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE Student NULL index NULL index_nameAge 18 NULL 3 33.33 Using where; Using index
使用到了index_nameAge索引,且使用到了覆盖索引。
第五步查询分析,非覆盖索引。
explain select name,age,email from Student where name like "%b%"
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE Student NULL ALL NULL NULL NULL NULL 3 33.33 Using where
没有使用到索引,全局扫描。