目标
掌握EXPLAIN使用方法; 明确SQL执行顺序; 明确SQL访问方式的效率等级; 明确SQL使用的具体索引。
语法
EXPLAIN SQL,例如:EXPLAIN select * from student;
EXPLAIN输出列
MySQL8.0官方释义
Column JSON Name Meaning id
select_id
The SELECT
identifier select_type
None The SELECT
type table
table_name
The table for the output row partitions
partitions
The matching partitions type
access_type
The join type possible_keys
possible_keys
The possible indexes to choose key
key
The index actually chosen key_len
key_length
The length of the chosen key ref
ref
The columns compared to the index rows
rows
Estimate of rows to be examined filtered
filtered
Percentage of rows filtered by table condition Extra
None Additional information
表示SQL的执行顺序。
如果id相同,SQL从上往下执行;id不相同,id值大的优先级更高,会先执行;id有相同也有不同,先执行id值大的SQL,
在执行相同的id时,从上往下执行。
表示SQL的查询类型。
MySQL8.0官方释义
select_type Value JSON Name Meaning SIMPLE None Simple SELECT (not using UNION or subqueries) PRIMARY None Outermost SELECT UNION None Second or later SELECT statement in a UNION DEPENDENT UNION dependent ( true ) Second or later SELECT statement in a UNION, dependent on outer query UNION RESULT union_result Result of a UNION. SUBQUERY None First SELECT in subquery DEPENDENT SUBQUERY dependent ( true ) First SELECT in subquery, dependent on outer query DERIVED None Derived table DEPENDENT DERIVED dependent ( true ) Derived table dependent on another table MATERIALIZED materialized_from_subquery Materialized subquery UNCACHEABLE SUBQUERY cacheable ( false ) A subquery for which the result cannot be cached and must be re-evaluated for each row of the outer query UNCACHEABLE UNION cacheable ( false ) The second or later select in a UNION that belongs to an uncacheable subquery (see UNCACHEABLE SUBQUERY)
表示SQL对应步骤访问的是哪个表或结果集。
表示访问类型,访问类型的效率从高到低如下:
system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range
> index > ALL
ALL表示全表扫描,一般情况下需要进行优化;
index大多是使用覆盖索引或者进行了索引排序;
range对索引进行了范围查询,且返回结果集中只有索引列,常见的范围操作:=, <>, >, >=, <, <=, BETWEEN, IN();
ref_or_null对同一个字段进行了IS NULL和=判断,或对同一个字段进行了IS NULL和in判断;
ref对非唯一索引进行了=判断(in也可以,但括号中只能由一个值。),包含关联后字段的等值匹配;
eq_ref对唯一索引进行了=判断(in也可以,但括号中只能由一个值。),包含关联后字段的等值匹配;
const使用了唯一索引为条件,且记录只有一行;
system该表只有一行(=系统表)。这是const联接类型的特例。
可能用到的索引。
实际使用到的索引。
表示索引中使用的字节数,可以通过key_len计算查询中使用的索引长度,在不损失精度的情况下长度越短越好。
显示索引的哪一列被使用了,如果可能的话,是一个常数。
估算SQL返回的总行数。
按表条件过滤的行百分比。
附加信息。
using filesort:说明mysql无法利用索引进行排序,只能利用排序算法进行排序;
using index:这个表示当前的查询时覆盖索引的,直接从索引中读取数据,而不用访问数据表;
using where:使用where进行条件过滤;
impossible where:where语句的结果总是false。
备注
《MySQL8.0官方文档》