Home  >  Article  >  Database  >  MySQL advanced learning: in-depth understanding of the explain command

MySQL advanced learning: in-depth understanding of the explain command

青灯夜游
青灯夜游forward
2021-09-24 11:33:422325browse

This article is an advanced study of MySQL. It will give you an in-depth understanding of the meaning of each field. I hope it will be helpful to you!

MySQL advanced learning: in-depth understanding of the explain command

What is the use of explain: In order to know how to optimize the execution of SQL statements, you need to view the specific execution process of SQL statements to speed up the execution efficiency of SQL statements.

You can use explain SQL statements to simulate the optimizer's execution of SQL query statements, so as to know how mysql processes sql statements. Understand whether the executor is processing SQL as we thought by looking at the execution plan.

explainThe information contained in the execution plan is as follows:

id: query sequence number

select_type: query type

table: table name or Alias

partitions: matching partition

type: access type

possible_keys: possible index

key: actual used index

key_len: Index length

ref: Column compared with index

rows: Estimated number of rows

filtered: Percentage of rows filtered by table conditions

Extra: Extra information

Let’s talk about the meaning of each column and the corresponding sql.

The test uses mysql version 5.7. The three table structures used are as follows

CREATE TABLE `demo`.`emp`  (  `emp_id` bigint(20) NOT NULL,  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '姓名',  `empno` int(20) NOT NULL COMMENT '工号',  `deptno` int(20) NOT NULL COMMENT '部门编号',  `sal` int(11) NOT NULL DEFAULT 0 COMMENT '销售量',  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 '部门编码',  `dname` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '部门名称',  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;

id column

select query sequence Number (a group of numbers), indicating the order in which select clauses or operation tables are executed in the query.

The id column is divided into three situations:

1. If the id is the same, then the execution order is from top to bottom

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;

MySQL advanced learning: in-depth understanding of the explain command

## 2 . If the id is different, if it is a subquery, the sequence number of the id will be incremented. The larger the id value, the higher the priority, and the earlier it will be executed


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

MySQL advanced learning: in-depth understanding of the explain command## 3. The same and different IDs exist at the same time: the same ones can be considered as a group, and are executed sequentially from top to bottom. Among all groups, the larger the ID value, the higher the priority, and the earlier they are executed

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 wheree.deptno = (select d.deptno from dept d where d.dname = 'SALES');

MySQL advanced learning: in-depth understanding of the explain command

MySQL advanced learning: in-depth understanding of the explain commandselect_type column is mainly used to distinguish the type of query, whether it is a normal query, a joint query or a subquery

1.

sample

: Simple query, excluding subqueries and union

mysql> explain select * from emp;

## 2. Primary: If the query contains any complex The subquery, the outermost query is marked as PrimaryMySQL advanced learning: in-depth understanding of the explain command

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

3. Union: In union, union all and the second and subsequent select in the subquery are Marked as unionMySQL advanced learning: in-depth understanding of the explain command

mysql> explain select * from emp where deptno = 10 union select * from emp where sal >2000;

## 4. Dependent union: In a large query containing UNION or UNION ALL, if each small query depends on the outer query, then except for the most Except for the small query on the left, the select_type value of the remaining small queries is 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)
MySQL advanced learning: in-depth understanding of the explain command

5. Union result: Select the result from the union table.

mysql> explain select * from emp where deptno = 10 union select * from emp where sal >2000;
MySQL advanced learning: in-depth understanding of the explain command

6. subquery: Contain subquery in select or where list (not in from clause)

mysql> explain select * from emp where sal > (select avg(sal) from emp) ;
MySQL advanced learning: in-depth understanding of the explain command

7. dependent subquery: The first select in the subquery (not in the from clause), and depends on the outer query.

mysql> explain select e1.* from emp e1 WHERE e1.deptno = (SELECT deptno FROM emp e2 WHERE e1.empno = e2.empno);
MySQL advanced learning: in-depth understanding of the explain command

8. derived: The subquery contained in the FROM list is marked as DERIVED, also called a derived class

mysql> explain select * from ( select emp_id,count(*) from emp group by emp_id ) e;

1MySQL advanced learning: in-depth understanding of the explain command

    9. UNCACHEABLE SUBQUERY:一个子查询的结果不能被缓存,必须重新评估外链接的第一行对于外层的主表,子查询不可被物化,每次都需要计算(耗时操作)

mysql> explain select * from emp where empno = (select empno from emp where deptno=@@sort_buffer_size);

1MySQL advanced learning: in-depth understanding of the explain command

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

table列

对应行正在访问哪一个表,表名或者别名,可能是临时表或者union合并结果集.

    1、如果是具体的表名,则表明从实际的物理表中获取数据,当然也可以是表的别名.

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

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

type列

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

访问的类型有很多,效率从最好到最坏依次是:

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

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

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

mysql> explain select * from emp;

MySQL advanced learning: in-depth understanding of the explain command

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

mysql> explain  select empno from emp;

MySQL advanced learning: in-depth understanding of the explain command

    3. range:表示利用索引查询的时候限制了范围,在指定范围内进行查询,这样避免了index的全索引扫描,适用的操作符:=, , >, >=,

mysql> explain select * from emp where empno between 100 and 200;

MySQL advanced learning: in-depth understanding of the explain command

    4. index_subquery:利用索引来关联子查询,不再扫描全表

mysql> explain select * from emp where deptno not in (select deptno from emp)

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

MySQL advanced learning: in-depth understanding of the explain command

    5. unique_subquery: 该连接类型类似于index_subquery,使用的是唯一索引

mysql> explain SELECT * from emp where emp_id not in (select emp.emp_id from emp );

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

MySQL advanced learning: in-depth understanding of the explain command

    6. index_merge:在查询过程中需要多个索引组合使用.

mysql> 没有模拟出来

    7. ref_or_null:对于某个字段即需要关联条件,也需要null值的情况下,查询优化器会选择这种访问方式.

mysql> 没模拟出来

    8. ref:使用了非唯一性索引进行数据的查找

mysql> explain select * from emp where  deptno=10;

MySQL advanced learning: in-depth understanding of the explain command

    9. eq_ref :当进行等值联表查询使用主键索引或者唯一性非空索引进行数据查找(实际上唯一索引等值查询type不是eq_ref而是const)

mysql> explain select * from salgrade s LEFT JOIN emp e on s.emp_id = e.emp_id;

MySQL advanced learning: in-depth understanding of the explain command

    10. const:最多只能匹配到一条数据,通常使用主键或唯一索引进行等值条件查询

mysql> explain select * from emp where empno = 10;

MySQL advanced learning: in-depth understanding of the explain command

    11. system:表只有一行记录(等于系统表),这是const类型的特例,平时不会出现,不需要进行磁盘io

mysql> explain SELECT * FROM `mysql`.`proxies_priv`;

MySQL advanced learning: in-depth understanding of the explain command

possible_keys列

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

key列

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

key_len列

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

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

ref列

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

rows列

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

filtered列

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

extra列

包含额外的信息。

    1. using filesort: 说明mysql无法利用索引进行排序,只能利用排序算法进行排序,会消耗额外的位置

mysql> explain select * from emp order by sal;

MySQL advanced learning: in-depth understanding of the explain command

    2. using temporary: 建立临时表来保存中间结果,查询完成之后把临时表删除

mysql> explain select name,count(*) from emp where deptno = 10 group by name;

MySQL advanced learning: in-depth understanding of the explain command

        3. using index: 这个表示当前的查询是覆盖索引的,直接从索引中读取数据,而不用访问数据表。如果同时出现using where 表名索引被用来执行索引键值的查找,如果没有,表面索引被用来读取数据,而不是真的查找

mysql> explain select deptno,count(*) from emp group by deptno limit 10;

MySQL advanced learning: in-depth understanding of the explain command

    4. using where: 使用where进行条件过滤

mysql> explain select * from emp where name = 1;

    5. using join buffer: 使用连接缓存

mysql> explain select * from emp e left join dept d on e.deptno = d.deptno;

MySQL advanced learning: in-depth understanding of the explain command

    6. impossible where:where语句的结果总是false

mysql> explain select * from emp where 1=0;

MySQL advanced learning: in-depth understanding of the explain command

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of MySQL advanced learning: in-depth understanding of the explain command. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:微信公众号--纪先生笔记. If there is any infringement, please contact admin@php.cn delete