zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

学MySQL执行计划觉今是而昨非

mysql执行 计划
2023-09-27 14:28:03 时间

目标

  1. 掌握EXPLAIN使用方法;
  2. 明确SQL执行顺序;
  3. 明确SQL访问方式的效率等级;
  4. 明确SQL使用的具体索引。

语法

EXPLAIN SQL,例如:EXPLAIN select * from student;


EXPLAIN输出列

MySQL8.0官方释义
ColumnJSON NameMeaning
idselect_idThe SELECT identifier
select_typeNoneThe SELECT type
tabletable_nameThe table for the output row
partitionspartitionsThe matching partitions
typeaccess_typeThe join type
possible_keyspossible_keysThe possible indexes to choose
keykeyThe index actually chosen
key_lenkey_lengthThe length of the chosen key
refrefThe columns compared to the index
rowsrowsEstimate of rows to be examined
filteredfilteredPercentage of rows filtered by table condition
ExtraNoneAdditional information
  • id

    表示SQL的执行顺序。
    如果id相同,SQL从上往下执行;id不相同,id值大的优先级更高,会先执行;id有相同也有不同,先执行id值大的SQL,
在执行相同的id时,从上往下执行。
  • select_type

    表示SQL的查询类型。
MySQL8.0官方释义
select_type ValueJSON NameMeaning
SIMPLENoneSimple SELECT (not using UNION or subqueries)
PRIMARYNoneOutermost SELECT
UNIONNoneSecond or later SELECT statement in a UNION
DEPENDENT UNIONdependent (true)Second or later SELECT statement in a UNION, dependent on outer query
UNION RESULTunion_resultResult of a UNION.
SUBQUERYNoneFirst SELECT in subquery
DEPENDENT SUBQUERYdependent (true)First SELECT in subquery, dependent on outer query
DERIVEDNoneDerived table
DEPENDENT DERIVEDdependent (true)Derived table dependent on another table
MATERIALIZEDmaterialized_from_subqueryMaterialized subquery
UNCACHEABLE SUBQUERYcacheable (false)A subquery for which the result cannot be cached and must be re-evaluated for each row of the outer query
UNCACHEABLE UNIONcacheable (false)The second or later select in a UNION that belongs to an uncacheable subquery (see UNCACHEABLE SUBQUERY)
  • table

    表示SQL对应步骤访问的是哪个表或结果集。
  • type

    表示访问类型,访问类型的效率从高到低如下:
    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联接类型的特例。
  • possible_keys

    可能用到的索引。
  • key

    实际使用到的索引。
  • key_len

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

    显示索引的哪一列被使用了,如果可能的话,是一个常数。
  • rows

    估算SQL返回的总行数。
  • filtered

    按表条件过滤的行百分比。
  • Extra

    附加信息。
    using filesort:说明mysql无法利用索引进行排序,只能利用排序算法进行排序;
    using index:这个表示当前的查询时覆盖索引的,直接从索引中读取数据,而不用访问数据表;
    using where:使用where进行条件过滤;
    impossible where:where语句的结果总是false。
    

备注

《MySQL8.0官方文档》