mysql like 原理_为什么Mysql 在覆盖索引下的like ‘%xxx%’查询能使用到索引,原理是什么?...

为什么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

没有使用到索引,全局扫描。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值