一、背景

今天,交流群有一位同学提出了一个问题。看下图:



之后,这位同学确实也发了一个全模糊查询走索引的例子:



到这我们可以发现,这两个sql最大的区别是:一个是查询全字段(select *),而一个只查询主键(select id)。

此时,又有其他同学讲了其他方案:



全文索引这个不用说,那是能让全模糊查询走索引的。但是索引覆盖这个方案,我觉得才是符合背景的:

1、因为提问的背景就是模糊查询字段是普通索引,而普通索引只查询主键就能用上覆盖索引。

2、并且背景中,就是只查询主键(ID)就显示用上索引了。

二、数据准备和场景重现

1、准备表和数据:

创建 user 表,给 phone 字段加了个普通索引:

CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_phone` (`phone`) USING BTREE COMMENT 'phone索引'
) ENGINE=InnoDB AUTO_INCREMENT=200007 DEFAULT CHARSET=utf8;

准备10万条数据意思意思:

delimiter ;
CREATE DEFINER=`root`@`localhost` PROCEDURE `iniData`()
begin
declare i int;
set i=1;
while(i<=100000)do
insert into user(name,age,phone) values('测试', i, 15627230000+i);
set i=i+1;
end while;
end;;
delimiter ; call iniData();

2、执行 SQL ,查看执行计划:

explain select * from user where phone like '%156%';
explain select id from user where phone like '%156%';

3、执行结果:

id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE user ALL 99927 11.11 Using where
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE user index index_phone 36 99927 11.11 Using where; Using index

我们可以发现,第二条 SQL 确实是显示用上了 index_phone 索引。

但是细心的同学可能会发现:possible_keys 竟然为空!有猫腻。。。

我这里先说一下 prossible_keys 和 key 的关系:

1、possible_keys 为可能使用的索引,而 key 是实际使用的索引;

2、正常是: key 的索引,必然会包含在 possible_keys 中。

还有猫腻一点就是:使用索引和不使用索引读取的行数(rows)竟然是一样的!

三、验证和阶段性猜想

上面讲到,possible_keyskey 的关系,那么我们利用正常的走索引来验证一下。

下面的 SQL, 不是全模糊查询,而是右模糊查询,保证是一定走索引的,我们分别看看此时 possible_keyskey 的值:

explain select id from user where phone like '156%';

执行结果:

id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE user range index_phone index_phone 36 49963 100 Using where; Using index

这里太明显了:

1、possible_keys 里确实包含了 key 里的索引。

2、 并且rows 瞬间降到 49963,整整降了一倍,并且 filtered 也达到了 100。

阶段猜想:

1、首先,select id from user where phone like '%156%'; 因为覆盖索引而用上了索引 index_phone

2、possible_keys 为 null,证明用不上索引的树形查找。很明显,select id from user where phone like '%156%'; 即使显示走了索引,但是读取行数 rowsselect * from user where phone like '%156%'; 没有走索引的 rows 是一样的。

3、那么,我们可以猜测到,select id from user where phone like '%156%'; 即使因为覆盖索引而用上了 index_phone 索引,但是却没用上树形查找,只是正常顺序遍历了索引树。所以说,其实这两条 SQL 在表字段不多的情况下,查询性能应该差不了多少。

四、通过 Trace 分析来验证

我们分别利用 Trace 分析对于这两个 SQL 优化器是如何选择的。

1、查询全字段:
-- 开启优化器跟踪
set session optimizer_trace='enabled=on';
select * from user where phone like '%156%';
-- 查看优化器追踪
select * from information_schema.optimizer_trace;

下面我们只看 TRACE 就行了:

{
"steps": [
{
"join_preparation": {
"select#": 1,
"steps": [
{
"expanded_query": "/* select#1 */ select `user`.`id` AS `id`,`user`.`name` AS `name`,`user`.`age` AS `age`,`user`.`phone` AS `phone` from `user` where (`user`.`phone` like '%156%')"
}
]
}
},
{
"join_optimization": {
"select#": 1,
"steps": [
{
"condition_processing": {
"condition": "WHERE",
"original_condition": "(`user`.`phone` like '%156%')",
"steps": [
{
"transformation": "equality_propagation",
"resulting_condition": "(`user`.`phone` like '%156%')"
},
{
"transformation": "constant_propagation",
"resulting_condition": "(`user`.`phone` like '%156%')"
},
{
"transformation": "trivial_condition_removal",
"resulting_condition": "(`user`.`phone` like '%156%')"
}
]
}
},
{
"substitute_generated_columns": {
}
},
{
"table_dependencies": [
{
"table": "`user`",
"row_may_be_null": false,
"map_bit": 0,
"depends_on_map_bits": [
]
}
]
},
{
"ref_optimizer_key_uses": [
]
},
{
"rows_estimation": [
{
"table": "`user`",
"table_scan": {
"rows": 99927,
"cost": 289
}
}
]
},
{
"considered_execution_plans": [
{
"plan_prefix": [
],
"table": "`user`",
"best_access_path": {
"considered_access_paths": [
{
"rows_to_scan": 99927,
"access_type": "scan", // 顺序扫描
"resulting_rows": 99927,
"cost": 20274,
"chosen": true
}
]
},
"condition_filtering_pct": 100,
"rows_for_plan": 99927,
"cost_for_plan": 20274,
"chosen": true
}
]
},
{
"attaching_conditions_to_tables": {
"original_condition": "(`user`.`phone` like '%156%')",
"attached_conditions_computation": [
],
"attached_conditions_summary": [
{
"table": "`user`",
"attached": "(`user`.`phone` like '%156%')"
}
]
}
},
{
"refine_plan": [
{
"table": "`user`"
}
]
}
]
}
},
{
"join_execution": {
"select#": 1,
"steps": [
]
}
}
]
}
2、只查询主键
set session optimizer_trace='enabled=on';
select id from user where phone like '%156%';
-- 查看优化器追踪
select * from information_schema.optimizer_trace;

下面我们继续只看 TRACE 就行了:

{
"steps": [
{
"join_preparation": {
"select#": 1,
"steps": [
{
"expanded_query": "/* select#1 */ select `user`.`id` AS `id` from `user` where (`user`.`phone` like '%156%')"
}
]
}
},
{
"join_optimization": {
"select#": 1,
"steps": [
{
"condition_processing": {
"condition": "WHERE",
"original_condition": "(`user`.`phone` like '%156%')",
"steps": [
{
"transformation": "equality_propagation",
"resulting_condition": "(`user`.`phone` like '%156%')"
},
{
"transformation": "constant_propagation",
"resulting_condition": "(`user`.`phone` like '%156%')"
},
{
"transformation": "trivial_condition_removal",
"resulting_condition": "(`user`.`phone` like '%156%')"
}
]
}
},
{
"substitute_generated_columns": {
}
},
{
"table_dependencies": [
{
"table": "`user`",
"row_may_be_null": false,
"map_bit": 0,
"depends_on_map_bits": [
]
}
]
},
{
"ref_optimizer_key_uses": [
]
},
{
"rows_estimation": [
{
"table": "`user`",
"table_scan": {
"rows": 99927,
"cost": 289
}
}
]
},
{
"considered_execution_plans": [
{
"plan_prefix": [
],
"table": "`user`",
"best_access_path": {
"considered_access_paths": [
{
"rows_to_scan": 99927,
"access_type": "scan", // 顺序扫描
"resulting_rows": 99927,
"cost": 20274,
"chosen": true
}
]
},
"condition_filtering_pct": 100,
"rows_for_plan": 99927,
"cost_for_plan": 20274,
"chosen": true
}
]
},
{
"attaching_conditions_to_tables": {
"original_condition": "(`user`.`phone` like '%156%')",
"attached_conditions_computation": [
],
"attached_conditions_summary": [
{
"table": "`user`",
"attached": "(`user`.`phone` like '%156%')"
}
]
}
},
{
"refine_plan": [
{
"table": "`user`"
}
]
}
]
}
},
{
"join_execution": {
"select#": 1,
"steps": [
]
}
}
]
}

好了,到这里我们可以发现,在 Trace 分析里面,都没显示优化器为这两个 SQL 实际选择了什么索引,而只是显示了都是用了 顺序扫描 的方式去查找数据。

可能唯一不同点就是:一个使用了主键索引的全表扫描,而另外一个是使用了普通索引的全表扫描;但是两个都没用上树形查找,也就是没用上 B+Tree 的特性来提升查询性能。

六、最后总结

1、当全模糊查询的 SQL 只查询主键作为结果集时,因为覆盖索引,会用上查询字段对应的索引。

2、即使用上了索引,但是却没用上树形查找的特性,只是正常的顺序遍历。

3、而正常的全表扫描也是主键索引的顺序遍历,所以说,其实这两者的性能其实是差不多的。

【MySQL 原理分析】之 Explain & Trace 深入分析全模糊查询走索引的原理的更多相关文章

  1. MySQL性能分析及explain的使用

    MySQL性能分析及explain用法的知识 1.使用explain语句去查看分析结果 如explain select * from test1 where id=1;会出现:id  selectty ...

  2. MySQL性能分析及explain的使用说明

    1.使用explain语句去查看分析结果 如explain select * from test1 where id=1;会出现:id selecttype table type possible_k ...

  3. Mysql数据库表排序规则不一致导致联表查询,索引不起作用问题

    Mysql数据库表排序规则不一致导致联表查询,索引不起作用问题 表更描述: 将mysql数据库中的worktask表添加ishaspic字段. 具体操作:(1)数据库worktask表新添是否有图片字 ...

  4. 【MySQL 原理分析】之 Trace 分析 order by 的索引原理

    一.背景 昨天早上,交流群有一位同学提出了一个问题.看下图: 我不是大佬,而且当时我自己的想法也只是猜测,所以并没有回复那位同学,只是接下来自己做了一个测试验证一下. 他只简单了说了一句话,就是同样的 ...

  5. MySQL性能分析之Explain

    目录 Explain基础 Explain进阶 Explain基础 关于explain命令相信大家并不陌生,具体用法和字段含义可以参考官网explain-output ,这里需要强调rows是核心指标, ...

  6. 神奇的 SQL 之 MySQL 性能分析神器 → EXPLAIN,SQL 起飞的基石!

    前言 开心一刻 某人养了一头猪,烦了想放生,可是猪认识回家的路,放生几次它都自己回来了.一日,这个人想了个狠办法,开车带着猪转了好多路进山区放生,放生后又各种打转,然后掏出电话给家里人打了个电话,问道 ...

  7. MySQL实现强制查询走索引和强制查询不缓存

    0.表结构如下:(包含两个索引) Create Table: CREATE TABLE `user` ( `userID` ) NOT NULL, `userCode` ) DEFAULT NULL, ...

  8. MySQL Index--NOT IN和不等于两类操作无法走索引?

    经常被问,NOT IN和<>操作就无法走索引? 真想只有一个:具体问题具体分析,没有前提的问题都是耍流氓. 准备测试数据: ## 删除测试表 DROP TABLE IF EXISTS tb ...

  9. Oracle,Mysql ,SQL Server 三大数据库带参数的模糊查询, 拼接查询条件问题

    最近项目开发一直在不断切换数据库,有时候一条sql 要同时考虑多种数据库中的兼容问题 , 先总结一条模糊查询拼接查询条件的问题,后续追加总结. 目前使用   mybatis: 1. Oracle 中使 ...

随机推荐

  1. Codeforces Round #572 (Div. 1) 差E

    Codeforces Round #572 (Div. 1) A2 题意:给一棵树,带边权,互不相同且为偶数.每次操作是选两个叶子然后在路径上同时加一个数.初始边权全是0,求一个操作序列使得最终边权与 ...

  2. 基于STC89C516的多游戏实现

    所用器件:STC89C516,矩阵键盘,LCD1602,16*16点阵,74HC595,无源蜂鸣器,晶振为11.0592MHZ 使用说明: 开机(复位)进入启动界面,1602显示Welcome.500 ...

  3. Yii框架的学习指南(策码秀才篇)1-1 如何认识Yii framework

    Yii的框架和其他框架的区别在于:它是更加 快速,安全,专业的PHP框架 Yii是一个高性能的,适用于开发WEB2.0应用的PHP框架. Yii是一个基于组件.用于开发大型 Web 应用的 高性能 P ...

  4. 吴裕雄--天生自然python学习笔记:打开文件并显示文件内容

    Win32com 组件打开文件通过 Documents 的 Open 方法,语法为 : 例如,打开上一节创建的 testl . docx 文件 , 文件变量名为 doc: 获得文件内容的方法有两种,第 ...

  5. 手撸GBDT原理(未完成)

    一直对GBDT里面的具体计算逻辑不太清楚,在网上发现了一篇好博客. 先上总结的关系图 GBDT对类别变量是怎么处理的? 这些东西都是在网上发现的,讲的挺好的. GBDT原理与Sklearn源码分析-回 ...

  6. java基础之异常 · fossi

    在开发中,异常处理是一个不可绕开的话题,我们对于异常的处理已经非常熟练了,对于异常本身的概念.用法等不再赘述了,直接结合面试问题来加深对异常的理解吧. Throwable 可以用来表示任何可以作为异常 ...

  7. Python之configparser配置文件的读取

    配置文件名 config.ini 文件内容: [linux] ip:10.0.13.26 port:22 username:root password:W2ynE6b58wheeFho [mysql] ...

  8. SpringMVC基本使用步骤

    使用Spring MVC,第一步就是使用Spring提供的前置控制器,即Servlet的实现类DispatcherServlet拦截url:org.springframework.web.servle ...

  9. Mybatis 入门之resultMap与resultType讲解实例

    resultMap:适合使用返回值是自定义实体类的情况 resultType:适合使用返回值得数据类型是非自定义的,即jdk的提供的类型 resultMap : type:映射实体类的数据类型 id: ...

  10. unittest(20)- 自动更新表格中数据(5)

    # 1. get_data.py from tools import project_path import pandas as pd class GetData: Cookie = None Add ...