一、背景
在日常工作中,可能会收到一些超时或慢响应的告警,最根到底可能是因为一些执行时间比较的SQL语句,这就跟我们平时开发需要注意细节相关了。那么找到这些SQL语句怎么优化呢?到底是哪里的问题导致SQL执行时间长呢? 这个时候Explain命令尤其重要,它可以查看该SQL语句有没有使用上索引、使用了哪个索引、有没有做全表扫描、有没有使用临时表等等。下面都是基于mysql 8进行案例说明的。
二、语法
EXPLAIN语句提供有关MySQL如何执行语句的信息。 EXPLAIN 通常与SELECT,DELETE,INSERT,REPLACE和UPDATE语句一起使用。
例如:explain select * from tb_student;
三、explain 输出列详解
Column |
JSON Name |
Meaning |
select_id |
The SELECT identifier |
|
None |
The SELECT type |
|
table_name |
The table for the output row |
|
partitions |
The matching partitions |
|
access_type |
The join type |
|
possible_keys |
The possible indexes to choose |
|
key |
The index actually chosen |
|
key_length |
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 |
|
None |
Additional information |
example:
1 2 3 4 5 |
|
- id:select标志符,有几个 select 就有几个id,并且id的顺序是按 select 出现的顺序增长的。MySQL将 select 查询分为简单查询和复杂查询。复杂查询可以如下:
1
2
3
4
5
6
7
mysql> explain
select
(
select
1
from
t limit 1)
from
t1;
+
----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type |
table
| partitions | type | possible_keys |
key
| key_len | ref |
rows
| filtered | Extra |
+
----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| 1 |
PRIMARY
| t1 |
NULL
|
index
|
NULL
|
PRIMARY
| 4 |
NULL
| 1 | 100.00 | Using
index
|
| 2 | SUBQUERY | t |
NULL
|
index
|
NULL
| idx_id | 5 |
NULL
| 1 | 100.00 | Using
index
|
+
----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
- select_type
select_type 表示对应行是是简单还是复杂的查询。总共有12种类型,挑其中几种描述下:
-
- simple:简单查询。查询不包含子查询和union
1
2
3
4
5
6
mysql> explain
select
*
from
t;
+
----+-------------+-------+------------+-------+---------------+--------+---------+------+------+----------+-------------+
| id | select_type |
table
| partitions | type | possible_keys |
key
- simple:简单查询。查询不包含子查询和union