【MySQL 原理分析】之 Explain & Trace 深入分析全模糊查询走索引的原理

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

【MySQL 原理分析】之 Explain & Trace 深入分析全模糊查询走索引的原理
一、背景
今天,交流群有一位同学提出了一个问题。看下图:

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

到这我们可以发现,这两个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_keys 和 key 的关系,那么我们利用正常的走索引来验证一下。

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

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%'; 即使显示走了索引,但是读取行数 rows 和 select * 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、而正常的全表扫描也是主键索引的顺序遍历,所以说,其实这两者的性能其实是差不多的。

原文地址https://www.cnblogs.com/Howinfun/p/12449975.html

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
10天前
|
关系型数据库 MySQL 索引
mysql 分析5语句的优化--索引添加删除
mysql 分析5语句的优化--索引添加删除
11 0
|
16天前
|
存储 关系型数据库 MySQL
轻松入门MySQL:优化进销存管理,掌握MySQL索引,提升系统效率(11)
轻松入门MySQL:优化进销存管理,掌握MySQL索引,提升系统效率(11)
|
10天前
|
SQL 缓存 关系型数据库
mysql性能优化-慢查询分析、优化索引和配置
mysql性能优化-慢查询分析、优化索引和配置
76 0
|
16天前
|
缓存 关系型数据库 MySQL
MySQL查询优化:提速查询效率的13大秘籍(合理使用索引合并、优化配置参数、使用分区优化性能、避免不必要的排序和group by操作)(下)
MySQL查询优化:提速查询效率的13大秘籍(合理使用索引合并、优化配置参数、使用分区优化性能、避免不必要的排序和group by操作)(下)
|
16天前
|
缓存 关系型数据库 MySQL
MySQL 查询优化:提速查询效率的13大秘籍(索引设计、查询优化、缓存策略、子查询优化以及定期表分析和优化)(中)
MySQL 查询优化:提速查询效率的13大秘籍(索引设计、查询优化、缓存策略、子查询优化以及定期表分析和优化)(中)
|
7天前
|
存储 关系型数据库 MySQL
【MySQL实战笔记】 04 | 深入浅出索引(上)-02
【4月更文挑战第9天】InnoDB数据库使用B+树作为索引模型,其中主键索引的叶子节点存储完整行数据,非主键索引则存储主键值。主键查询只需搜索一棵树,而非主键查询需两次搜索,因此推荐使用主键查询以提高效率。在插入新值时,B+树需要维护有序性,可能导致数据页分裂影响性能。自增主键在插入时可避免数据挪动和页分裂,且占用存储空间小,通常更为理想。然而,如果场景仅需唯一索引,可直接设为主键以减少查询步骤。
13 1
【MySQL实战笔记】 04 | 深入浅出索引(上)-02
|
9天前
|
关系型数据库 MySQL 数据库
6. 了解过Mysql的索引嘛 ?
了解MySQL的索引类型,包括单列索引(普通、唯一、主键和全文索引)和组合索引。单列索引用于一列,如普通索引允许重复值,唯一索引和主键索引不允许,后者不允许空值。全文索引适用于特定文本字段。组合索引是多列的,遵循左前缀原则,通常推荐用于提高查询效率,除非是主键。
12 0
|
11天前
|
关系型数据库 MySQL 数据库
mysql卸载、下载、安装(window版本)
mysql卸载、下载、安装(window版本)
|
1月前
|
关系型数据库 MySQL 数据库连接
关于MySQL-ODBC的zip包安装方法
关于MySQL-ODBC的zip包安装方法
|
29天前
|
关系型数据库 MySQL 数据库
rds安装数据库客户端工具
安装阿里云RDS的数据库客户端涉及在本地安装对应类型(如MySQL、PostgreSQL)的客户端工具。对于MySQL,可选择MySQL Command-Line Client或图形化工具如Navicat,安装后输入RDS实例的连接参数进行连接。对于PostgreSQL,可以使用`psql`命令行工具或图形化客户端如PgAdmin。首先从阿里云控制台获取连接信息,然后按照官方文档安装客户端,最后配置客户端连接以确保遵循安全指引。
82 1