原文地址:https://dev.mysql.com/doc/refman/5.7/en/explain-output.html

9.8.2 EXPLAIN Output Format

The EXPLAIN statement provides information about the execution plan for a SELECT statement.

EXPLAIN returns a row of information for each table used in the SELECT statement. It lists the tables in the output in the order that MySQL would read them while processing the statement. MySQL resolves all joins using a nested-loop join method. This means that MySQL reads a row from the first table, and then finds a matching row in the second table, the third table, and so on. When all tables are processed, MySQL outputs the selected columns and backtracks through the table list until a table is found for which there are more matching rows. The next row is read from this table and the process continues with the next table.

Before MySQL 5.7.3, when the EXTENDED keyword is used, EXPLAIN produces extra information that can be viewed by issuing a SHOW WARNINGS statement following the EXPLAIN statement. EXPLAIN EXTENDED also displays the filteredcolumn. See Section 9.8.3, “EXPLAIN EXTENDED Output Format”. As of MySQL 5.7.3, extended output is enabled by default and the EXTENDED keyword is unnecessary.

Note

You cannot use the EXTENDED and PARTITIONS keywords together in the same EXPLAIN statement. In addition, neither of these keywords can be used together with the FORMAT option. (FORMAT=JSON causes EXPLAIN to display extended and partition information automatically; using FORMAT=TRADITIONAL has no effect on EXPLAIN output.)

  • EXPLAIN Output Columns

  • EXPLAIN Join Types

  • EXPLAIN Extra Information

  • EXPLAIN Output Interpretation

EXPLAIN Output Columns

This section describes the output columns produced by EXPLAIN. Later sections provide additional information about the type and Extra columns.

Each output row from EXPLAIN provides information about one table. Each row contains the values summarized in Table 9.1, “EXPLAIN Output Columns”, and described in more detail following the table. Column names are shown in the table's first column; the second column provides the equivalent property name shown in the output when FORMAT=JSON is used.

Table 9.1 EXPLAIN Output Columns

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

Note

JSON properties which are NULL are not displayed in JSON-formatted EXPLAIN output.

EXPLAIN Join Types

The type column of EXPLAIN output describes how tables are joined. In JSON-formatted output, these are found as values of the access_type property. The following list describes the join types, ordered from the best type to the worst:

EXPLAIN Extra Information

The Extra column of EXPLAIN output contains additional information about how MySQL resolves the query. The following list explains the values that can appear in this column. Each item also indicates for JSON-formatted output which property displays the Extra value. For some of these, there is a specific property. The others display as the text of the message property.

If you want to make your queries as fast as possible, look out for Extra column values of Using filesort and Using temporary, or, in JSON-formatted EXPLAIN output, for using_filesort and using_temporary_table properties equal to true.

  • Child of 'table' pushed join@1 (JSON: message text)

    This table is referenced as the child of table in a join that can be pushed down to the NDB kernel. Applies only in MySQL Cluster, when pushed-down joins are enabled. See the description of the ndb_join_pushdown server system variable for more information and examples.

  • const row not found (JSON property: const_row_not_found)

    For a query such as SELECT ... FROM tbl_name, the table was empty.

  • Deleting all rows (JSON property: message)

    For DELETE, some storage engines (such as MyISAM) support a handler method that removes all table rows in a simple and fast way. This Extra value is displayed if the engine uses this optimization.

  • Distinct (JSON property: distinct)

    MySQL is looking for distinct values, so it stops searching for more rows for the current row combination after it has found the first matching row.

  • FirstMatch(tbl_name) (JSON property: first_match)

    The semi-join FirstMatch join shortcutting strategy is used for tbl_name.

  • Full scan on NULL key (JSON property: message)

    This occurs for subquery optimization as a fallback strategy when the optimizer cannot use an index-lookup access method.

  • Impossible HAVING (JSON property: message)

    The HAVING clause is always false and cannot select any rows.

  • Impossible WHERE (JSON property: message)

    The WHERE clause is always false and cannot select any rows.

  • Impossible WHERE noticed after reading const tables (JSON property: message)

    MySQL has read all const (and system) tables and notice that the WHERE clause is always false.

  • LooseScan(m..n) (JSON property: message)

    The semi-join LooseScan strategy is used. m and n are key part numbers.

  • No matching min/max row (JSON property: message)

    No row satisfies the condition for a query such as SELECT MIN(...) FROM ... WHERE condition.

  • no matching row in const table (JSON property: message)

    For a query with a join, there was an empty table or a table with no rows satisfying a unique index condition.

  • No matching rows after partition pruning (JSON property: message)

    For DELETE or UPDATE, the optimizer found nothing to delete or update after partition pruning. It is similar in meaning to Impossible WHERE for SELECT statements.

  • No tables used (JSON property: message)

    The query has no FROM clause, or has a FROM DUAL clause.

    For INSERT or REPLACE statements, EXPLAIN displays this value when there is no SELECT part. For example, it appears for EXPLAIN INSERT INTO t VALUES(10) because that is equivalent to EXPLAIN INSERT INTO t SELECT 10 FROM DUAL.

  • Not exists (JSON property: message)

    MySQL was able to do a LEFT JOIN optimization on the query and does not examine more rows in this table for the previous row combination after it finds one row that matches the LEFT JOIN criteria. Here is an example of the type of query that can be optimized this way:

    SELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.idWHERE t2.id IS NULL;
    

    Assume that t2.id is defined as NOT NULL. In this case, MySQL scans t1 and looks up the rows in t2 using the values of t1.id. If MySQL finds a matching row in t2, it knows that t2.id can never be NULL, and does not scan through the rest of the rows in t2 that have the same id value. In other words, for each row in t1, MySQL needs to do only a single lookup in t2, regardless of how many rows actually match in t2.

  • Plan isn't ready yet (JSON property: none)

    This value occurs with EXPLAIN FOR CONNECTION when the optimizer has not finished creating the execution plan for the statement executing in the named connection. If execution plan output comprises multiple lines, any or all of them could have this Extra value, depending on the progress of the optimizer in determining the full execution plan.

  • Range checked for each record (index map: N) (JSON property: message)

    MySQL found no good index to use, but found that some of indexes might be used after column values from preceding tables are known. For each row combination in the preceding tables, MySQL checks whether it is possible to use a rangeor index_merge access method to retrieve rows. This is not very fast, but is faster than performing a join with no index at all. The applicability criteria are as described in Section 9.2.1.3, “Range Optimization”, and Section 9.2.1.4, “Index Merge Optimization”, with the exception that all column values for the preceding table are known and considered to be constants.

    Indexes are numbered beginning with 1, in the same order as shown by SHOW INDEX for the table. The index map value N is a bitmask value that indicates which indexes are candidates. For example, a value of 0x19 (binary 11001) means that indexes 1, 4, and 5 will be considered.

  • Scanned N databases (JSON property: message)

    This indicates how many directory scans the server performs when processing a query for INFORMATION_SCHEMA tables, as described in Section 9.2.4, “Optimizing INFORMATION_SCHEMA Queries”. The value of N can be 0, 1, or all.

  • Select tables optimized away (JSON property: message)

    The optimizer determined 1) that at most one row should be returned, and 2) that to produce this row, a deterministic set of rows must be read. When the rows to be read can be read during the optimization phase (for example, by reading index rows), there is no need to read any tables during query execution.

    The first condition is fulfilled when the query is implicitly grouped (contains an aggregate function but no GROUP BY clause). The second condition is fulfilled when one row lookup is performed per index used. The number of indexes read determines the number of rows to read.

    Consider the following implicitly grouped query:

    SELECT MIN(c1), MIN(c2) FROM t1;
    

    Suppose that MIN(c1) can be retrieved by reading one index row and MIN(c2) can be retrieved by reading one row from a different index. That is, for each column c1 and c2, there exists an index where the column is the first column of the index. In this case, one row is returned, produced by reading two deterministic rows.

    This Extra value does not occur if the rows to read are not deterministic. Consider this query:

    SELECT MIN(c2) FROM t1 WHERE c1 <= 10;
    

    Suppose that (c1, c2) is a covering index. Using this index, all rows with c1 <= 10 must be scanned to find the minimum c2 value. By contrast, consider this query:

    SELECT MIN(c2) FROM t1 WHERE c1 = 10;
    

    In this case, the first index row with c1 = 10 contains the minimum c2 value. Only one row must be read to produce the returned row.

    For storage engines that maintain an exact row count per table (such as MyISAM, but not InnoDB), this Extra value can occur for COUNT(*) queries for which the WHERE clause is missing or always true and there is no GROUP BY clause. (This is an instance of an implicitly grouped query where the storage engine influences whether a deterministic number of rows can be read.)

  • Skip_open_tableOpen_frm_onlyOpen_full_table (JSON property: message)

    These values indicate file-opening optimizations that apply to queries for INFORMATION_SCHEMA tables, as described in Section 9.2.4, “Optimizing INFORMATION_SCHEMA Queries”.

    • Skip_open_table: Table files do not need to be opened. The information has already become available within the query by scanning the database directory.

    • Open_frm_only: Only the table's .frm file need be opened.

    • Open_full_table: The unoptimized information lookup. The .frm.MYD, and .MYI files must be opened.

  • Start temporaryEnd temporary (JSON property: message)

    This indicates temporary table use for the semi-join Duplicate Weedout strategy.

  • unique row not found (JSON property: message)

    For a query such as SELECT ... FROM tbl_name, no rows satisfy the condition for a UNIQUE index or PRIMARY KEY on the table.

  • Using filesort (JSON property: using_filesort)

    MySQL must do an extra pass to find out how to retrieve the rows in sorted order. The sort is done by going through all rows according to the join type and storing the sort key and pointer to the row for all rows that match the WHERE clause. The keys then are sorted and the rows are retrieved in sorted order. See Section 9.2.1.15, “ORDER BY Optimization”.

  • Using index (JSON property: using_index)

    The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index.

    For InnoDB tables that have a user-defined clustered index, that index can be used even when Using index is absent from the Extra column. This is the case if type is index and key is PRIMARY.

  • Using index condition (JSON property: using_index_condition)

    Tables are read by accessing index tuples and testing them first to determine whether to read full table rows. In this way, index information is used to defer (“push down”) reading full table rows unless it is necessary. See Section 9.2.1.6, “Index Condition Pushdown Optimization”.

  • Using index for group-by (JSON property: using_index_for_group_by)

    Similar to the Using index table access method, Using index for group-by indicates that MySQL found an index that can be used to retrieve all columns of a GROUP BY or DISTINCT query without any extra disk access to the actual table. Additionally, the index is used in the most efficient way so that for each group, only a few index entries are read. For details, see Section 9.2.1.16, “GROUP BY Optimization”.

  • Using join buffer (Block Nested Loop)Using join buffer (Batched Key Access) (JSON property: using_join_buffer)

    Tables from earlier joins are read in portions into the join buffer, and then their rows are used from the buffer to perform the join with the current table. (Block Nested Loop) indicates use of the Block Nested-Loop algorithm and(Batched Key Access) indicates use of the Batched Key Access algorithm. That is, the keys from the table on the preceding line of the EXPLAIN output will be buffered, and the matching rows will be fetched in batches from the table represented by the line in which Using join buffer appears.

    In JSON-formatted output, the value of using_join_buffer is always either one of Block Nested Loop or Batched Key Access.

  • Using MRR (JSON property: message)

    Tables are read using the Multi-Range Read optimization strategy. See Section 9.2.1.13, “Multi-Range Read Optimization”.

  • Using sort_union(...)Using union(...)Using intersect(...) (JSON property: message)

    These indicate how index scans are merged for the index_merge join type. See Section 9.2.1.4, “Index Merge Optimization”.

  • Using temporary (JSON property: using_temporary_table)

    To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query contains GROUP BY and ORDER BY clauses that list columns differently.

  • Using where (JSON property: attached_condition)

    WHERE clause is used to restrict which rows to match against the next table or send to the client. Unless you specifically intend to fetch or examine all rows from the table, you may have something wrong in your query if the Extra value is not Using where and the table join type is ALL or index.

    Using where has no direct counterpart in JSON-formatted output; the attached_condition property contains any WHERE condition used.

  • Using where with pushed condition (JSON property: message)

    This item applies to NDB tables only. It means that MySQL Cluster is using the Condition Pushdown optimization to improve the efficiency of a direct comparison between a nonindexed column and a constant. In such cases, the condition is“pushed down” to the cluster's data nodes and is evaluated on all data nodes simultaneously. This eliminates the need to send nonmatching rows over the network, and can speed up such queries by a factor of 5 to 10 times over cases where Condition Pushdown could be but is not used. For more information, see Section 9.2.1.5, “Engine Condition Pushdown Optimization”.

  • Zero limit (JSON property: message)

    The query had a LIMIT 0 clause and cannot select any rows.

EXPLAIN Output Interpretation

You can get a good indication of how good a join is by taking the product of the values in the rows column of the EXPLAIN output. This should tell you roughly how many rows MySQL must examine to execute the query. If you restrict queries with the max_join_size system variable, this row product also is used to determine which multiple-table SELECT statements to execute and which to abort. See Section 6.1.1, “Configuring the Server”.

The following example shows how a multiple-table join can be optimized progressively based on the information provided by EXPLAIN.

Suppose that you have the SELECT statement shown here and that you plan to examine it using EXPLAIN:

EXPLAIN SELECT tt.TicketNumber, tt.TimeIn,tt.ProjectReference, tt.EstimatedShipDate,tt.ActualShipDate, tt.ClientID,tt.ServiceCodes, tt.RepetitiveID,tt.CurrentProcess, tt.CurrentDPPerson,tt.RecordVolume, tt.DPPrinted, et.COUNTRY,et_1.COUNTRY, do.CUSTNAMEFROM tt, et, et AS et_1, doWHERE tt.SubmitTime IS NULLAND tt.ActualPC = et.EMPLOYIDAND tt.AssignedPC = et_1.EMPLOYIDAND tt.ClientID = do.CUSTNMBR;

For this example, make the following assumptions:

  • The columns being compared have been declared as follows.

    Table Column Data Type
    tt ActualPC CHAR(10)
    tt AssignedPC CHAR(10)
    tt ClientID CHAR(10)
    et EMPLOYID CHAR(15)
    do CUSTNMBR CHAR(15)
  • The tables have the following indexes.

    Table Index
    tt ActualPC
    tt AssignedPC
    tt ClientID
    et EMPLOYID (primary key)
    do CUSTNMBR (primary key)
  • The tt.ActualPC values are not evenly distributed.

Initially, before any optimizations have been performed, the EXPLAIN statement produces the following information:

table type possible_keys key  key_len ref  rows  Extra
et    ALL  PRIMARY       NULL NULL    NULL 74
do    ALL  PRIMARY       NULL NULL    NULL 2135
et_1  ALL  PRIMARY       NULL NULL    NULL 74
tt    ALL  AssignedPC,   NULL NULL    NULL 3872ClientID,ActualPCRange checked for each record (index map: 0x23)

Because type is ALL for each table, this output indicates that MySQL is generating a Cartesian product of all the tables; that is, every combination of rows. This takes quite a long time, because the product of the number of rows in each table must be examined. For the case at hand, this product is 74 × 2135 × 74 × 3872 = 45,268,558,720 rows. If the tables were bigger, you can only imagine how long it would take.

One problem here is that MySQL can use indexes on columns more efficiently if they are declared as the same type and size. In this context, VARCHAR and CHAR are considered the same if they are declared as the same size. tt.ActualPC is declared as CHAR(10) and et.EMPLOYID is CHAR(15), so there is a length mismatch.

To fix this disparity between column lengths, use ALTER TABLE to lengthen ActualPC from 10 characters to 15 characters:

mysql> ALTER TABLE tt MODIFY ActualPC VARCHAR(15);

Now tt.ActualPC and et.EMPLOYID are both VARCHAR(15). Executing the EXPLAIN statement again produces this result:

table type   possible_keys key     key_len ref         rows    Extra
tt    ALL    AssignedPC,   NULL    NULL    NULL        3872    UsingClientID,                                         whereActualPC
do    ALL    PRIMARY       NULL    NULL    NULL        2135Range checked for each record (index map: 0x1)
et_1  ALL    PRIMARY       NULL    NULL    NULL        74Range checked for each record (index map: 0x1)
et    eq_ref PRIMARY       PRIMARY 15      tt.ActualPC 1

This is not perfect, but is much better: The product of the rows values is less by a factor of 74. This version executes in a couple of seconds.

A second alteration can be made to eliminate the column length mismatches for the tt.AssignedPC = et_1.EMPLOYID and tt.ClientID = do.CUSTNMBR comparisons:

mysql> ALTER TABLE tt MODIFY AssignedPC VARCHAR(15),->                MODIFY ClientID   VARCHAR(15);

After that modification, EXPLAIN produces the output shown here:

table type   possible_keys key      key_len ref           rows Extra
et    ALL    PRIMARY       NULL     NULL    NULL          74
tt    ref    AssignedPC,   ActualPC 15      et.EMPLOYID   52   UsingClientID,                                         whereActualPC
et_1  eq_ref PRIMARY       PRIMARY  15      tt.AssignedPC 1
do    eq_ref PRIMARY       PRIMARY  15      tt.ClientID   1

At this point, the query is optimized almost as well as possible. The remaining problem is that, by default, MySQL assumes that values in the tt.ActualPC column are evenly distributed, and that is not the case for the tt table. Fortunately, it is easy to tell MySQL to analyze the key distribution:

mysql> ANALYZE TABLE tt;

With the additional index information, the join is perfect and EXPLAIN produces this result:

table type   possible_keys key     key_len ref           rows Extra
tt    ALL    AssignedPC    NULL    NULL    NULL          3872 UsingClientID,                                        whereActualPC
et    eq_ref PRIMARY       PRIMARY 15      tt.ActualPC   1
et_1  eq_ref PRIMARY       PRIMARY 15      tt.AssignedPC 1
do    eq_ref PRIMARY       PRIMARY 15      tt.ClientID   1

The rows column in the output from EXPLAIN is an educated guess from the MySQL join optimizer. Check whether the numbers are even close to the truth by comparing the rows product with the actual number of rows that the query returns. If the numbers are quite different, you might get better performance by using STRAIGHT_JOIN in your SELECT statement and trying to list the tables in a different order in the FROM clause. (However, STRAIGHT_JOIN may prevent indexes from being used because it disables semi-join transformations. See Section 9.2.1.18.1, “Optimizing Subqueries with Semi-Join Transformations”.)

It is possible in some cases to execute statements that modify data when EXPLAIN SELECT is used with a subquery; for more information, see Section 14.2.10.8, “Subqueries in the FROM Clause”.

转载于:https://www.cnblogs.com/davidwang456/p/5985630.html

看懂mysql执行计划--官方文档相关推荐

  1. 看懂 MySQL 执行计划花费不到十来分钟

    通常查询慢查询SQL语句时会使用EXPLAIN命令来查看SQL语句的执行计划,通过返回的信息,可以了解到Mysql优化器是如何执行SQL语句,通过分析可以帮助我们提供优化的思路. 1. Explain ...

  2. 看懂Oracle执行计划(转载)

    转载自 写的很好,屯一波 最近一直在跟Oracle打交道,从最初的一脸懵逼到现在的略有所知,也来总结一下自己最近所学,不定时更新ing- 一:什么是Oracle执行计划? 执行计划是一条查询语句在Or ...

  3. Oracle调优之看懂Oracle执行计划

    1.文章写作前言简介 之前曾经拜读过<收获,不止sql调优>一书,此书是国内DBA写的一本很不错的调优类型的书,是一些很不错的调优经验的分享.虽然读了一遍,做了下读书笔记,觉得很有所收获, ...

  4. 6.读懂mysql执行计划

    文章目录 1.执行计划概念和语法 1.执行计划的概念 2.执行计划的语法 1.常规执行计划语法 2.扩展执行计划的语法 3.分区表的执行计划语法 2.执行计划包含的信息 1.id​:查询的顺序 2.s ...

  5. 如何看懂ORACLE执行计划

    一.什么是执行计划 An explain plan is a representation of the access path that is taken when a query is execu ...

  6. storm mysql trident_Apache Storm 官方文档 —— Trident 教程

    Trident 是 Storm 的一种高度抽象的实时计算模型,它可以将高吞吐量(每秒百万级)数据输入.有状态的流式处理与低延时的分布式查询无缝结合起来.如果你了解 Pig 或者 Cascading 这 ...

  7. mysql中括号_手把手教你看MySQL官方文档

    前言: 在学习和使用MySQL的过程中,难免会遇到各种问题.不知道当你遇到相关问题时会怎么做,我在工作或写文章的过程中,遇到不懂或需要求证的问题时通常会去查阅官方文档.慢慢的,阅读文档也有了一些经验, ...

  8. mysql官方文档中文版_手把手教你看MySQL官方文档

    前言: 在学习和使用MySQL的过程中,难免会遇到各种问题.不知道当你遇到相关问题时会怎么做,我在工作或写文章的过程中,遇到不懂或需要求证的问题时通常会去查阅官方文档.慢慢的,阅读文档也有了一些经验, ...

  9. mysql执行计划缓存在哪_怎么去看懂mysql的执行计划

    mysql的查看执行计划的语句很简单,explain+你要执行的sql语句就OK了. 举一个例子 EXPLAIN SELECT * from employees where employees.gen ...

最新文章

  1. AI:2020年6月22日北京智源大会演讲分享之机器感知专题论坛—14:10-14:50王亮教授《面向复杂视觉任务的视觉认知计算》
  2. 从零开始配置MySQL MMM
  3. 谣言粉碎机 - 极短时间内发送两个Odata request,前一个会自动被cancel掉?
  4. 【DI专题】在 DI 脚本文件中调用存储过程
  5. 开关电源雷击浪涌整改_雷击浪涌的防护解析!
  6. 5.1.6 UPDATE更新数据
  7. HTTP之一:http协议简介(3)
  8. Ubuntu16.04 安装Spyder问题
  9. 高质量C编程00-汇总
  10. fastboot工具的操作流程
  11. Python解微分方程(验证数学建模第五版火箭发射模型)
  12. 无线WAPI网络AS鉴权服务器,WAPI是什么意思?苹果iPhone手机启用WAPI有什么作用?...
  13. ETL数据同步工具Kettle简介
  14. DRM2.0 的身份认证过程
  15. CDH安装指南——酒仙网技术
  16. 针对顽固dll后缀文件删除
  17. HTML技能点--设置网页图标标志
  18. C#最小二乘法进行曲线拟合及相关系数
  19. word表格怎么缩小上下间距_word表格怎么调整行高间距拉不动
  20. 基于ElasticsearchRepository进行简单封装实现非空更新,saveOrUpdate[笔记]

热门文章

  1. python dateformatter_Python dates.DateFormatter方法代码示例
  2. 剪切工具怎么用_原创度检测工具是怎么用的?优质的内容更容易获得平台推荐...
  3. 设置超链接的HTML标签是______,如何对a超链接标签中包含的HTML标签进行样式设置...
  4. php常量定义表达式,从表达式创建PHP类常量的最佳解决方法?
  5. pythonwhile循环结束语句_Python while循环语句
  6. python 回归去掉共线性_以IPL数据集为例的线性回归技术概述
  7. 文本编辑器实现跳转到指定行的功能
  8. oracle12c默认字符集,修改Oracle【12C】字符集
  9. c语言 getch头文件,用getch()需要头文件吗?
  10. python 读取txt