MySQL进阶系列:一文详解explain

explain有何用处呢: 为了知道优化SQL语句的执行,需要查看SQL语句的具体执行过程,以加快SQL语句的执行效率。

​ 可以使用explain+SQL语句来模拟优化器执行SQL查询语句,从而知道mysql是如何处理sql语句的。通过查看执行计划了解执行器是否按照我们想的那样处理SQL。

​ 官网地址: https://dev.mysql.com/doc/refman/5.5/en/explain-output.html

1、执行计划中包含的信息

Column Meaning id The SELECT

identifier select_type The SELECT

type,查询类型 table The table for the output row partitions The matching partitions type The join type 访问类型 possible_keys The possible indexes to choose key The index actually chosen key_len The length of the chosen key ref The columns compared to the index rows Estimate of rows to be examined filtered Percentage of rows filtered by table condition extra Additional information

id列

select查询的序列号(一组数字),表示查询中执行select子句或者操作表的顺序

id号分为三种情况:

​ 1、如果id相同,那么执行顺序从上到下

mysql> explain select * from emp e join dept d on e.deptno = d.deptno join salgrade sg on e.sal between sg.losal and sg.hisal;

+----+-------------+-------+------------+...

| id | select_type | table | partitions |...

+----+-------------+-------+------------+...

|  1 | SIMPLE      | e     | NULL       |...

|  1 | SIMPLE      | d     | NULL       |...

|  1 | SIMPLE      | sg    | NULL       |...

+----+-------------+-------+------------ ...

​ 2、如果id不同,如果是子查询,id的序号会递增,id值越大优先级越高,越先被执行

mysql> explain select * from emp e where e.deptno = (select d.deptno from dept d where d.dname = 'SALES');

+----+-------------+-------+------------+...

| id | select_type | table | partitions |...

+----+-------------+-------+------------+...

|  1 | PRIMARY     | e     | NULL       |...

|  2 | SUBQUERY    | d     | NULL       |...

+----+-------------+-------+------------ ...

​ 3、id相同和不同的,同时存在:相同的可以认为是一组,从上往下顺序执行,在所有组中,id值越大,优先级越高,越先执行

mysql> explain select * from emp e join dept d on e.deptno = d.deptno join salgrade sg on e.sal between sg.losal and sg.hisal where e.deptno = (select d.deptno from dept d where d.dname = 'SALES');

+----+-------------+-------+------------+...

| id | select_type | table | partitions |...

+----+-------------+-------+------------+...

|  1 | PRIMARY     | e     | NULL       |...

|  1 | PRIMARY     | d     | NULL       |...

|  1 | PRIMARY     | sg    | NULL       |...

|  2 | SUBQUERY    | d     | NULL       |...

+----+-------------+-------+------------ ...

MySQL进阶系列:一文详解explain

select_type列

主要用来分辨查询的类型,是普通查询还是联合查询还是子查询 select_type

Value Meaning SIMPLE 不包含子查询或者 UNION PRIMARY 查询中若包含任何复杂的子部分,最外层查询被标记为 PRIMARY UNION 在union,union all和子查询中的第二个和随后的select被标记为union DEPENDENT UNION 在包含UNION或者UNION ALL的大查询中,如果各个小查询都依赖于外层查询的话,那除了最左边的那个小查询之外,其余的小查询的select_type的值就是DEPENDENT UNION UNION RESULT 从union中获取结果 SUBQUERY 子查询中的第一个select(不在from子句中) DEPENDENT SUBQUERY 子查询中的第一个select(不在from子句中),而且取决于外面的查询 DERIVED 在FROM列表中包含的子查询被标记为DERIVED UNCACHEABLE SUBQUERY 一个子查询的结果不能被缓存,必须重新评估外链接的第一行对于外层的主表,子查询不可被物化,每次都需要计算(耗时操作) UNCACHEABLE UNION UNION操作中,内层的不可被物化的子查询(类似于UNCACHEABLE SUBQUERY)

--sample:简单的查询,不包含子查询和union
mysql> explain select * from emp;

+----+-------------+-------+------------+...

| id | select_type | table | partitions |...

+----+-------------+-------+------------+...

|  1 | SIMPLE      | emp   | NULL       |...

+----+-------------+-------+------------ ...

--primary:查询中若包含任何复杂的子查询,最外层查询则被标记为Primary
mysql> explain select * from emp e where e.deptno = (select d.deptno from dept d where d.dname = 'SALES');

+----+-------------+-------+------------+...

| id | select_type | table | partitions |...

+----+-------------+-------+------------+...

|  1 | PRIMARY     | e     | NULL       |...

|  2 | SUBQUERY    | d     | NULL       |...

+----+-------------+-------+------------ ...

--union:在union,union all和子查询中的第二个和随后的select被标记为union
mysql> explain select * from emp where deptno = 10 union select * from emp where sal >2000;

+------+--------------+------------+...

| id   | select_type  | table      |...

+------+--------------+------------+...

|  1   | PRIMARY      | emp        |...

|  2   | UNION        | emp        |...

| NULL | UNION RESULT |  |...

+----+--------------+------------+...

--dependent union:在包含UNION或者UNION ALL的大查询中,如果各个小查询都依赖于外层查询的话,那除了最左边的那个小查询之外,其余的小查询的select_type的值就是DEPENDENT UNION
mysql> explain select * from emp e where e.empno  in ( select empno from emp where deptno = 10 union select empno from emp where sal >2000)

+------+--------------------+------------+...

| id   | select_type        | table      |...

+------+--------------------+------------+...

|  1   | PRIMARY            | e          |...

|  2   | DEPENDENT SUBQUERY | emp        |...

|  3   | DEPENDENT UNION    | emp        |...

| NULL | UNION RESULT       |  | ...

+----+--------------------+------------+....

--union result:从union表获取结果的select
mysql> explain select * from emp where deptno = 10 union select * from emp where sal >2000;

+------+--------------+------------+...

| id   | select_type  | table      |...

+------+--------------+------------+...

|  1   | PRIMARY      | emp        |...

|  2   | UNION        | emp        |...

| NULL | UNION RESULT |  |...

+------+--------------+------------+...

--subquery:在select或者where列表中包含子查询(不在from子句中)
mysql> explain select * from emp where sal > (select avg(sal) from emp) ;

+----+-------------+-------+------------+...

| id | select_type | table | partitions |...

+----+-------------+-------+------------+...

|  1 | PRIMARY     | emp   | NULL       |...

|  2 | SUBQUERY    | dmp   | NULL       |...

+----+-------------+-------+------------ ...

--dependent subquery: 子查询中的第一个select(不在from子句中),而且取决于外面的查询
mysql> explain select e1.* from emp e1 WHERE e1.deptno = (SELECT deptno FROM emp e2 WHERE e1.empno = e2.empno);

+----+--------------------+------------+...

| id | select_type        | table      |...

+----+--------------------+------------+...

|  1 | PRIMARY            | e1         |...

|  2 | DEPENDENT SUBQUERY | e2        |...

+----+--------------------+------------+....

--DERIVED: from子句中出现的子查询,也叫做派生类,
mysql> explain select * from ( select emp_id,count(*) from emp group by emp_id ) e;

+----+-------------+------------+...

| id | select_type | table      |...

+----+-------------+------------+...

|  1 | PRIMARY     |  |...

|  2 | DERIVED     | emp        |...

+----+-------------+------------+...

--UNCACHEABLE SUBQUERY:表示使用子查询的结果不能被缓存
mysql> explain select * from emp where empno = (select empno from emp where deptno=@@sort_buffer_size);

 +----+----------------------+-------------+...

| id | select_type          | table       |...

+----+----------------------+-------------+...

|  1 | PRIMARY              | emp         |...

|  2 | UNCACHEABLE SUBQUERY | emp         |...

+----+----------------------+-------------+....

--uncacheable union: 表示union的查询结果不能被缓存(没找到具体的sql语句验证)

table列

对应行正在访问哪一个表,表名或者别名,可能是临时表或者union合并结果集
1、如果是具体的表名,则表明从实际的物理表中获取数据,当然也可以是表的别名

​ 2、表名是derivedN的形式,表示使用了id为N的查询产生的衍生表

​ 3、当有union result的时候,表名是union n1,n2等的形式,n1,n2表示参与union的id

type列

type显示的是访问类型,访问类型表示我是以何种方式去访问我们的数据,最容易想的是全表扫描,直接暴力的遍历一张表去寻找需要的数据,效率非常低下。

接入类型很多,效率从好到差依次为:

[En]

There are many types of access, and the efficiency is from the best to the worst:

system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL

一般情况下,得保证查询至少达到range级别,最好能达到ref

--all:全表扫描,需要扫描整张表,从头到尾找到需要的数据行。一般情况下出现这样的sql语句而且数据量比较大的话那么就需要进行优化。
mysql> explain select * from emp;

+----+-------------+-------+------------+------+---------------+
| id | select_type | table | partitions | type | possible_keys |
+----+-------------+-------+------------+------+---------------+
|  1 | SIMPLE      | emp   | NULL       | ALL  | NULL          |
+----+-------------+-------+------------+------+---------------+

--index:全索引扫描这个比all的效率要好,主要有两种情况,一种是当前的查询时覆盖索引,即我们需要的数据在索引中就可以索取,或者是使用了索引进行排序,这样就避免数据的重排序
mysql> explain  select empno from emp;

+----+-------------+-------+------------+------+---------------+
| id | select_type | table | partitions | type | possible_keys |
+----+-------------+-------+------------+------+---------------+
|  1 | SIMPLE      | emp   | NULL       | index| NULL          |
+----+-------------+-------+------------+------+---------------+

最后要达到这个级别range
--range:表示利用索引查询的时候限制了范围,在指定范围内进行查询,这样避免了index的全索引扫描,适用的操作符: =, <>, >, >=,  explain select * from emp where empno between 100 and 200;

+----+-------------+-------+------------+------+---------------+
| id | select_type | table | partitions | type | possible_keys |
+----+-------------+-------+------------+------+---------------+
|  1 | SIMPLE      | emp   | NULL       |range | u2            |
+----+-------------+-------+------------+------+---------------+

--index_subquery:利用索引来关联子查询,不再扫描全表
mysql> explain select * from emp where deptno not in (select deptno from emp)

+----+--------------------+-------+------------+----------------+---------------+...

| id | select_type        | table | partitions | type           | possible_keys |...

+----+--------------------+-------+------------+----------------+---------------+...

|  1 | PRIMARY            | emp   | NULL       | ALL            | NULL          |...

|  2 | DEPENDENT SUBQUERY | emp   | NULL       | index_subquery | u1            |...

+----+--------------------+-------+------------+----------------+---------------+...

但是大多数情况下使用SELECT子查询时,MySQL查询优化器会自动将子查询优化为联表查询,因此 type 不会显示为 index_subquery,而是ref

--unique_subquery:该连接类型类似与index_subquery,使用的是唯一索引
mysql> explain SELECT * from emp where emp_id not in (select emp.emp_id from emp );

+----+--------------------+-------+------------+-----------------+---------------+...

| id | select_type        | table | partitions | type            | possible_keys |...

+----+--------------------+-------+------------+-----------------+---------------+...

|  1 | PRIMARY            | emp   | NULL       | ALL             | NULL          |...

|  2 | DEPENDENT SUBQUERY | emp   | NULL       | unique_subquery | PRIMARY       |...

+----+--------------------+-------+------------+-----------------+---------------+...

大多数情况下使用SELECT子查询时,MySQL查询优化器会自动将子查询优化为联表查询,因此 type 不会显示为 index_subquery,而是eq_ref

--index_merge:在查询过程中需要多个索引组合使用
mysql> 没有模拟出来

--ref_or_null:对于某个字段即需要关联条件,也需要null值的情况下,查询优化器会选择这种访问方式
mysql> 没模拟出来

--ref:使用了非唯一性索引进行数据的查找
mysql> explain select * from emp where  deptno=10;

+----+-------------+-------+------------+------+---------------+...

| id | select_type | table | partitions | type | possible_keys |...

+----+-------------+-------+------------+------+---------------+...

|  1 | SIMPLE      | emp   | NULL       | ref  | u1            |...

+----+-------------+-------+------------+------+---------------+...

--eq_ref :当进行等值联表查询使用主键索引或者唯一性非空索引进行数据查找
> 实际上唯一索引等值查询type不是eq_ref而是const
mysql> explain select * from salgrade s LEFT JOIN emp e on s.emp_id = e.emp_id;

+----+-------------+-------+------------+--------+---------------+...

| id | select_type | table | partitions | type   | possible_keys |...

+----+-------------+-------+------------+--------+---------------+...

|  1 | SIMPLE      | s     | NULL       | ALL    | NULL          |...

|  1 | SIMPLE      | e     | NULL       | eq_ref | PRIMARY       |...

+----+-------------+-------+------------+--------+---------------+...

--const:最多只能匹配到一条数据,通常使用主键或唯一索引进行等值条件查询
mysql> explain select * from emp where empno = 10;

+----+-------------+-------+------------+-------+---------------+...

| id | select_type | table | partitions | type  | possible_keys |...

+----+-------------+-------+------------+-------+---------------+...

|  1 | SIMPLE      | emp   | NULL       | const | u2            |...

+----+-------------+-------+------------+-------+---------------+...

--system:表只有一行记录(等于系统表),这是const类型的特例,平时不会出现,不需要进行磁盘io
mysql> explain SELECT * FROM mysql.proxies_priv;

+----+-------------+--------------+------------+--------+---------------+...

| id | select_type | table        | partitions | type   | possible_keys |...

+----+-------------+--------------+------------+--------+---------------+...

|  1 | SIMPLE      | proxies_priv | NULL       | system | NULL          |...

+----+-------------+--------------+------------+--------+---------------+...

possible_keys列

​ 显示可能应用在这张表中的索引,一个或多个,查询涉及到的字段上若存在索引,则该索引将被列出,但不一定被查询实际使用。

key列

​ 实际使用的索引,如果为null,则没有使用索引,查询中若使用了覆盖索引,则该索引和查询的select字段重叠。

key_len

表示索引中使用的字节数,可以通过key_len计算查询中使用的索引长度,在不损失精度的情况下长度越短越好。

索引越大占用存储空间越大,这样io的次数和量就会增加,影响执行效率

ref列

显示之前的表在key列记录的索引中查找值所用的列或者常量

rows列

根据表的统计信息及索引使用情况,大致估算出找出所需记录需要读取的行数,此参数很重要,直接反应的sql找了多少数据,在完成目的的情况下越少越好。

filtered列

针对表中符合某个条件(where子句或者联接条件)的记录数的百分比所做的一个悲观估算。

extra

包含额外的信息。

--using filesort:说明mysql无法利用索引进行排序,只能利用排序算法进行排序,会消耗额外的位置
mysql> explain select * from emp order by sal;

...+------+---------------+------+---------+------+------+----------+----------------+
...| type | possible_keys | key  | key_len | ref  | rows | filtered | Extra          |
...+------+---------------+------+---------+------+------+----------+----------------+
...| ALL  | NULL          | NULL | NULL    | NULL |    2 |   100.00 | Using filesort |
...+------+---------------+------+---------+------+------+----------+----------------+

--using temporary:建立临时表来保存中间结果,查询完成之后把临时表删除
mysql> explain select name,count(*) from emp where deptno = 10 group by name;

...+------+---------+-------+------+----------+---------------------------------+
...| key  | key_len | ref   | rows | filtered | Extra                           |
...+------+---------+-------+------+----------+---------------------------------+
...| u1   | 4       | const |    2 |   100.00 | Using temporary; Using filesort |
...+------+---------+-------+------+----------+---------------------------------+

--using index:这个表示当前的查询时覆盖索引的,直接从索引中读取数据,而不用访问数据表。如果同时出现using where 表名索引被用来执行索引键值的查找,如果没有,表面索引被用来读取数据,而不是真的查找
mysql> explain select deptno,count(*) from emp group by deptno limit 10;

...+------+---------+------+------+----------+-------------+
...| key  | key_len | ref  | rows | filtered | Extra       |
...+------+---------+------+------+----------+-------------+
...| u1   | 4       | NULL |    2 |   100.00 | Using index |
...+------+---------+------+------+----------+-------------+

--using where:使用where进行条件过滤
mysql> explain select * from emp where name = 1;

--using join buffer:使用连接缓存
mysql> explain select * from emp e left join dept d on e.deptno = d.deptno;

...+------+---------+------+------+----------+---------------------------------------+
...| key  | key_len | ref  | rows | filtered | Extra                                 |
...+------+---------+------+------+----------+---------------------------------------+
...| NULL | NULL    | NULL |    2 |   100.00 | NULL                                  |
...| NULL | NULL    | NULL |    1 |   100.00 | Using join buffer (Block Nested Loop) |
...+------+---------+------+------+----------+---------------------------------------+

--impossible where:where语句的结果总是false
mysql> explain select * from emp where 1=0;

...+------+---------+------+------+----------+------------------+
...| key  | key_len | ref  | rows | filtered | Extra            |
...+------+---------+------+------+----------+------------------+
...| NULL | NULL    | NULL | NULL |     NULL | Impossible WHERE |
...+------+---------+------+------+----------+------------------+

测试使用mysql版本5.7, 使用的3个表结构如下

CREATE TABLE demo.emp  (
  emp_id bigint(20) NOT NULL,
  name varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '&#x59D3;&#x540D;',
  empno int(20) NOT NULL COMMENT '&#x5DE5;&#x53F7;',
  deptno int(20) NOT NULL COMMENT '&#x90E8;&#x95E8;&#x7F16;&#x53F7;',
  sal int(11) NOT NULL DEFAULT 0 COMMENT '&#x9500;&#x552E;&#x91CF;',
  PRIMARY KEY (emp_id) USING BTREE,
  INDEX u1(deptno) USING BTREE,
  UNIQUE INDEX u2(empno) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

CREATE TABLE demo.dept  (
  id bigint(20) NOT NULL,
  deptno int(20) NOT NULL COMMENT '&#x90E8;&#x95E8;&#x7F16;&#x7801;',
  dname varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '&#x90E8;&#x95E8;&#x540D;&#x79F0;',
  PRIMARY KEY (id) USING BTREE,
  UNIQUE INDEX dept_u1(deptno) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

CREATE TABLE demo.salgrade  (
  id bigint(20) NOT NULL,
  losal int(20) NULL DEFAULT NULL,
  hisal int(20) NULL DEFAULT NULL,
  emp_id bigint(20) NULL DEFAULT NULL,
  PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

MySQL高级相关更多内容,如事务,锁,MVCC,读写分离,分库分表等还在持续更新中,欢迎关注催更。

欢迎关注公众号: 纪先生笔记

MySQL进阶系列:一文详解explain

MySQL系列的历史文章

  1. MySQL进阶系列:一文了解mysql基础架构;
  2. MySQL进阶系列:一文了解mysql存储引擎;
  3. MySQL进阶系列:mysql中MyISAM和InnoDB有什么区别;
  4. MySQL进阶系列:mysql中表设计如何更好的选择数据类型;
  5. MySQL进阶系列:数据库设计中的范式究竟该如何使用;

Original: https://www.cnblogs.com/sunjiguang/p/15271936.html
Author: 纪先生笔记
Title: MySQL进阶系列:一文详解explain

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/508142/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 适用于顺序磁盘访问的1分钟法则

    预备知识梳理 本文中设定 block size 与 page size 大小相等。 什么是 Block 文章的开始先解释一下,磁盘的数据读写是以扇区 (sector) 为单位的,而…

    数据库 2023年6月14日
    0100
  • 21粤比武

    先进行密码绕过,在这个界面迅速按下方向键,然后按下e进入编辑模式 找到linux16这一行,将lang编码后面的全部删掉,加上 <span class=”ne-text”&g…

    数据库 2023年6月11日
    0104
  • 钻石价格预测的ML全流程!从模型构建调优道部署应用!⛵

    💡 作者:韩信子@ShowMeAI📘 数据分析 ◉ 技能提升系列:http://www.showmeai.tech/tutorials/33📘 AI 面试题库系列:http://w…

    数据库 2023年6月15日
    095
  • Linux常用指令

    Linux常用指令 到达底部 运行级别有以下几种 0级:关机 1级:单用户 (找回密码) 2级: 多用户没有网络服务 3级: 多用户有网络服务 4级: 系统未使用保留给用户 5级:…

    数据库 2023年6月16日
    090
  • Java异步执行器CompletableFuture源码解析

    CompletableFuture是对 Future的一种强有力的扩展, Future只能通过轮询 isDone()方法或者调用 get()阻塞等待获取一个异步任务的结果,才能继续…

    数据库 2023年6月11日
    090
  • 使用 yum 在 CentOS7 上安装 MySQL8

    时间:2022-07-13安装版本:MySQL-community-8.0.29 0. 删除MariaDB 在CentOS 7中默认有安装MariaDB,这个是MySQL的分支,通…

    数据库 2023年6月16日
    0103
  • 【StoneDB Class】入门第二课:StoneDB整体架构解析

    StoneDB 的整体架构分为三层,分别是应用层、服务层和存储引擎层。应用层主要负责客户端的连接管理和权限验证;服务层提供了 SQL 接口、查询缓存、解析器、优化器、执行器等组件;…

    数据库 2023年5月24日
    074
  • Servlet中跨域问题详解

    一、什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实施的安全限制。 浏览器从一个域名的网页去请求另一个域名的资源时…

    数据库 2023年6月14日
    099
  • Git的常见命令

    Git 一、git环境安装 1.初始化本地仓库: git init 2.将本地仓库跟远程仓库建立连接:git remote add name path ​ git clone pa…

    数据库 2023年6月16日
    083
  • 515. 在每个树行中找最大值

    515. 在每个树行中找最大值 给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。 示例1: 输入: root = [1,3,2,5,3,null,9]输出: […

    数据库 2023年6月16日
    0103
  • IDEA 常用插件

    插件使用参考:Idea插件系列 插件名称 说明 IDE Eval Reset 破解软件 Alibaba Java Coding Guidelines 阿里巴巴开发规范 tabnin…

    数据库 2023年6月6日
    090
  • Nginx平滑升级版本

    Nginx平滑升级版本 一, 查看现目前版本,准备预升级版本的安装包 #查看nginx版本 /usr/local/nginx/sbin/nginx -v #测试nginx访问是否正…

    数据库 2023年6月11日
    088
  • 没有发生GC也进入了安全点?这段关于安全点的JVM源码有点意思!

    文末 JVM 思维导图,有需要的可以自取 熟知并发编程的你认为下面这段代码的执行结果是怎么样的? 我如果说,执行流程是: t1 线程和 t2 线程一直执行 num 的累加操作 主线…

    数据库 2023年6月16日
    0101
  • Activiti 7 源码学习

    启动分析 源码版本是 7.1.0.M6 首先从 ProcessEngineAutoConfiguration 开始 ProcessEngineAutoConfiguration 是…

    数据库 2023年6月14日
    096
  • Collection

    ArrayList底层使用了数组存储 LinkedList底层使用双向链表 HashSet底层是一个HashMap支持,HashMap底层物理实现一个Hash表 LinkedHas…

    数据库 2023年6月14日
    099
  • 最新Spring Boot 跨域配置,亲测好用

    背景: 网上有很多跨域配置,但都存在各种各样问题;经过改良和测试后,最终形成一个稳定配置版本,我的Spring Boot版本是2.5.1 问题: 前后端分离后,进行联调,发现浏览器…

    数据库 2023年6月6日
    0111
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球