8.4 中文镜像

MySQL 8.4 参考手册 · 中文镜像

正文为中文,英文原文默认隐藏。点击任意中文段落即可展开 / 收起对应英文原文。

打开官方英文原文 ↗

译文由机器翻译生成,仅供理解参考;有疑问请以官方英文原文为准。

中文点击中文段落可显示 / 隐藏英文原文本页译文覆盖 100%

15.8.2 EXPLAIN 语句15.8.2 EXPLAIN Statement

{EXPLAIN | DESCRIBE | DESC}
    tbl_name [col_name | wild]

{EXPLAIN | DESCRIBE | DESC}
    [explain_type] [INTO variable]
    {[schema_spec] explainable_stmt | FOR CONNECTION connection_id}

{EXPLAIN | DESCRIBE | DESC} ANALYZE [FORMAT = TREE] [schema_spec] select_statement

explain_type: {
    FORMAT = format_name
}

format_name: {
    TRADITIONAL
  | JSON
  | TREE
}

explainable_stmt: {
    SELECT statement
  | TABLE statement
  | DELETE statement
  | INSERT statement
  | REPLACE statement
  | UPDATE statement
}

schema_spec:
FOR {SCHEMA | DATABASE} schema_name

DESCRIBE 和 EXPLAIN 语句是同义词。实际上,DESCRIBE 关键字更常用于获取表结构信息,而 EXPLAIN 用于获取查询执行计划(即 MySQL 如何执行查询的说明)。The DESCRIBE and EXPLAIN statements are synonyms. In practice, the DESCRIBE keyword is more often used to obtain information about table structure, whereas EXPLAIN is used to obtain a query execution plan (that is, an explanation of how MySQL would execute a query).

以下讨论使用了 DESCRIBE 和 EXPLAIN 关键词,但 MySQL 解析器将它们完全视为同义词。The following discussion uses the DESCRIBE and EXPLAIN keywords in accordance with those uses, but the MySQL parser treats them as completely synonymous.

获取表结构信息Obtaining Table Structure Information

DESCRIBE 提供表列信息:DESCRIBE provides information about the columns in a table:

mysql> DESCRIBE City;
+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| Id         | int(11)  | NO   | PRI | NULL    | auto_increment |
| Name       | char(35) | NO   |     |         |                |
| Country    | char(3)  | NO   | UNI |         |                |
| District   | char(20) | YES  | MUL |         |                |
| Population | int(11)  | NO   |     | 0       |                |
+------------+----------+------+-----+---------+----------------+

DESCRIBE是SHOW COLUMNS的快捷方式。这些语句还显示视图的信息。有关SHOW COLUMNS的输出列提供了更多信息。参见第 15.7.7.6 节,“SHOW COLUMNS 语句”.DESCRIBE is a shortcut for SHOW COLUMNS. These statements also display information for views. The description for SHOW COLUMNS provides more information about the output columns. See Section 15.7.7.6, “SHOW COLUMNS Statement”.

By default, DESCRIBE displays information about all columns in the table. col_name, if given, is the name of a column in the table. In this case, the statement displays information only for the named column. wild, if given, is a pattern string. It can contain the SQL %以及_ wildcard characters. In this case, the statement displays output only for the columns with names matching the string. There is no need to enclose the string within quotation marks unless it contains spaces or other special characters.By default, DESCRIBE displays information about all columns in the table. col_name, if given, is the name of a column in the table. In this case, the statement displays information only for the named column. wild, if given, is a pattern string. It can contain the SQL % and _ wildcard characters. In this case, the statement displays output only for the columns with names matching the string. There is no need to enclose the string within quotation marks unless it contains spaces or other special characters.

为兼容 Oracle,提供了DESCRIBE 语句。The DESCRIBE statement is provided for compatibility with Oracle.

SHOW CREATE TABLE“, SHOW TABLE STATUS, SHOW INDEX 语句也提供表的信息。参见 第 15.7.7 节,“SHOW 语句”。The SHOW CREATE TABLE, SHOW TABLE STATUS, and SHOW INDEX statements also provide information about tables. See Section 15.7.7, “SHOW Statements”.

explain_format系统变量在用于获取表列信息时,对 EXPLAIN。The explain_format system variable has no effect on the output of EXPLAIN when used to obtain information about table columns.

获取执行计划信息Obtaining Execution Plan Information

EXPLAIN 语句提供有关 MySQL 如何执行语句的信息:The EXPLAIN statement provides information about how MySQL executes statements:

  • EXPLAIN 与 SELECT, DELETE, INSERTREPLACE, UPDATE, TABLE 语句。EXPLAIN works with SELECT, DELETE, INSERT, REPLACE, UPDATE, and TABLE statements.

  • 当 EXPLAIN 与可解释语句一起使用时,MySQL 会显示优化器关于语句执行计划的信息。也就是说,MySQL 会解释它将如何处理该语句,包括有关表如何连接以及以何种顺序连接的信息。有关使用 EXPLAIN 获取执行计划信息的信息,请参见 第 10.8.2 节,“EXPLAIN 输出格式”。When EXPLAIN is used with an explainable statement, MySQL displays information from the optimizer about the statement execution plan. That is, MySQL explains how it would process the statement, including information about how tables are joined and in which order. For information about using EXPLAIN to obtain execution plan information, see Section 10.8.2, “EXPLAIN Output Format”.

  • 当 EXPLAIN 与 FOR CONNECTION connection_id 一起使用,而不是与可解释语句一起使用时,它会显示在指定连接中正在执行的语句的执行计划。请参见 第 10.8.4 节,“获取命名连接的执行计划信息”。When EXPLAIN is used with FOR CONNECTION connection_id rather than an explainable statement, it displays the execution plan for the statement executing in the named connection. See Section 10.8.4, “Obtaining Execution Plan Information for a Named Connection”.

  • 对于可解释语句,EXPLAIN 生成额外的执行计划信息,可通过 SHOW WARNINGS“。参见 第 10.8.3 节,”扩展 EXPLAIN 输出格式“。For explainable statements, EXPLAIN produces additional execution plan information that can be displayed using SHOW WARNINGS. See Section 10.8.3, “Extended EXPLAIN Output Format”.

  • EXPLAIN 对检查涉及分区表的查询非常有用。参见第 26.3.5 节,“获取分区信息”。EXPLAIN is useful for examining queries involving partitioned tables. See Section 26.3.5, “Obtaining Information About Partitions”.

  • 可以使用 FORMAT 选项来选择输出格式。TRADITIONAL 以表格格式呈现输出。如果没有 FORMAT表格格式。JSON 格式以 JSON 格式显示信息。TREE 提供树状输出,比 TRADITIONAL 格式更精确地描述查询处理;它是唯一显示哈希连接使用情况的格式(参见 第 10.2.1.4 节,“哈希连接优化”),并且始终用于 EXPLAIN ANALYZE)。The FORMAT option can be used to select the output format. TRADITIONAL presents the output in tabular format. This is the default if no FORMAT option is present. JSON format displays the information in JSON format. TREE provides tree-like output with more precise descriptions of query handling than the TRADITIONAL format; it is the only format which shows hash join usage (see Section 10.2.1.4, “Hash Join Optimization”) and is always used for EXPLAIN ANALYZE.

    在 MySQL 8.4 中,EXPLAIN(即没有FORMAT由explain_format系统变量。该变量的具体影响将在本节后面描述。In MySQL 8.4, the default output format used by EXPLAIN (that is, when it has no FORMAT option) is determined by the value of the explain_format system variable. The precise effects of this variable are described later in this section.

    MySQL 8.4 支持一个额外的 INTO 选项,EXPLAIN FORMAT=JSON可以将 JSON 格式的输出保存为用户变量,如下:MySQL 8.4 supports an additional INTO option with EXPLAIN FORMAT=JSON, which enables saving the JSON formatted output into a user variable, like this:

    mysql> EXPLAIN FORMAT=JSON INTO @myselect 
        ->     SELECT name FROM a WHERE id = 2;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SELECT @myselect\G
    *************************** 1. row ***************************
    @myex: {
      "query_block": {
        "select_id": 1,
        "cost_info": {
          "query_cost": "1.00"
        },
        "table": {
          "table_name": "a",
          "access_type": "const",
          "possible_keys": [
            "PRIMARY"
          ],
          "key": "PRIMARY",
          "used_key_parts": [
            "id"
          ],
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows_examined_per_scan": 1,
          "rows_produced_per_join": 1,
          "filtered": "100.00",
          "cost_info": {
            "read_cost": "0.00",
            "eval_cost": "0.10",
            "prefix_cost": "0.00",
            "data_read_per_join": "408"
          },
          "used_columns": [
            "id",
            "name"
          ]
        }
      }
    }
    1 row in set (0.00 sec)
    

    这适用于任何可解释语句(SELECT TABLE, INSERT, UPDATE, REPLACE, 或 DELETE这里展示了使用 UPDATE 和 DELETE 语句的示例:This works with any explainable statement (SELECT, TABLE, INSERT, UPDATE, REPLACE, or DELETE). Examples using UPDATE and DELETE statements are shown here:

    mysql> EXPLAIN FORMAT=JSON INTO @myupdate 
        ->   UPDATE a SET name2 = "garcia" WHERE id = 3;              
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> EXPLAIN FORMAT=JSON INTO @mydelete 
        ->     DELETE FROM a WHERE name1 LIKE '%e%';
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SELECT @myupdate, @mydelete\G
    *************************** 1. row ***************************
    @myupdate: {
      "query_block": {
        "select_id": 1,
        "table": {
          "update": true,
          "table_name": "a",
          "access_type": "range",
          "possible_keys": [
            "PRIMARY"
          ],
          "key": "PRIMARY",
          "used_key_parts": [
            "id"
          ],
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows_examined_per_scan": 1,
          "filtered": "100.00",
          "attached_condition": "(`db`.`a`.`id` = 3)"
        }
      }
    }
    @mydelete: {
      "query_block": {
        "select_id": 1,
        "table": {
          "delete": true,
          "table_name": "a",
          "access_type": "ALL",
          "rows_examined_per_scan": 2,
          "filtered": "100.00",
          "attached_condition": "(`db`.`a`.`name1` like '%e%')"
        }
      }
    }
    1 row in set (0.00 sec)
    

    你可以像处理其他 JSON 值一样,使用 MySQL JSON 函数来处理这个值,比如这些示例中使用 JSON_EXTRACT():You can work with this value using MySQL JSON functions as you would with any other JSON value, as in these examples using JSON_EXTRACT():

    mysql> SELECT JSON_EXTRACT(@myselect, "$.query_block.table.key");
    +----------------------------------------------------+
    | JSON_EXTRACT(@myselect, "$.query_block.table.key") |
    +----------------------------------------------------+
    | "PRIMARY"                                          |
    +----------------------------------------------------+
    1 row in set (0.01 sec)
    
    mysql> SELECT JSON_EXTRACT(@myupdate, "$.query_block.table.access_type") AS U_acc,
        ->        JSON_EXTRACT(@mydelete, "$.query_block.table.access_type") AS D_acc;
    +---------+-------+
    | U_acc   | D_acc |
    +---------+-------+
    | "range" | "ALL" |
    +---------+-------+
    1 row in set (0.00 sec)
    

    对于复杂语句,JSON 输出可能相当大;尤其是在读取时,将闭括号和开括号配对起来可能很困难;为了使 JSON 结构的键(如果有)在闭括号附近重复出现,可以设置 end_markers_in_json=ON你需要注意,虽然这会使输出更易读,但也会使 JSON 无效,导致 JSON 函数出现错误。For complex statements, the JSON output can be quite large; in particular, it can be difficult when reading it to pair the closing bracket and opening brackets; to cause the JSON structure's key, if it has one, to be repeated near the closing bracket, set end_markers_in_json=ON. You should be aware that while this makes the output easier to read, it also renders the JSON invalid, causing JSON functions to raise an error.

    另见 第 14.17 节,“JSON Functions”。See also Section 14.17, “JSON Functions”.

    尝试使用 INTO 子句而不明确包含 FORMAT=JSON EXPLAIN 被拒绝,ER_EXPLAIN_INTO_IMPLICIT_FORMAT_NOT_SUPPORTED。无论系统变量 explain_format。Trying to use an INTO clause without explicitly including FORMAT=JSON causes EXPLAIN to be rejected with ER_EXPLAIN_INTO_IMPLICIT_FORMAT_NOT_SUPPORTED. This is true regardless of the current value of the explain_format system variable.

    INTO 子句不支持 FOR CONNECTION。The INTO clause is not supported with FOR CONNECTION.

    INTO 也不支持 EXPLAIN ANALYZE 当 explain_json_format_version=1。INTO is also not supported with EXPLAIN ANALYZE when explain_json_format_version=1.

    Important

    如果因任何原因拒绝了要分析的语句,用户变量不会被更新。If, for any reason, the statement to be analyzed is rejected, the user variable is not updated.

  • MySQL 8.4 支持 FOR SCHEMA 子句,使 EXPLAIN 表现得像是要分析的语句在命名数据库中执行;FOR DATABASE 作为同义词支持。这里展示了一个简单的使用示例:MySQL 8.4 supports a FOR SCHEMA clause, which causes EXPLAIN to behave as if the statement to be analyzed had been executed in the named database; FOR DATABASE is supported as a synonym. A simple example of use is shown here:

    mysql> USE b;
    Database changed
    mysql> CREATE SCHEMA s1;
    Query OK, 1 row affected (0.01 sec)
    
    mysql> CREATE SCHEMA s2;
    Query OK, 1 row affected (0.01 sec)
    
    mysql> USE s1;
    Database changed
    mysql> CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, c2 INT NOT NULL);
    Query OK, 0 rows affected (0.04 sec)
    
    mysql> USE s2;
    Database changed
    mysql> CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, c2 INT NOT NULL, KEY i1 (c2));
    Query OK, 0 rows affected (0.04 sec)
    
    mysql> USE b;
    Database changed
    mysql> EXPLAIN FORMAT=TREE FOR SCHEMA s1 SELECT * FROM t WHERE c2 > 50\G
    *************************** 1. row ***************************
    EXPLAIN: -> Filter: (t.c2 > 50)  (cost=0.35 rows=1)
        -> Table scan on t  (cost=0.35 rows=1)
    
    1 row in set (0.00 sec)
    
    mysql> EXPLAIN FORMAT=TREE FOR SCHEMA s2 SELECT * FROM t WHERE c2 > 50\G
    *************************** 1. row ***************************
    EXPLAIN: -> Filter: (t.c2 > 50)  (cost=0.35 rows=1)
        -> Covering index scan on t using i1  (cost=0.35 rows=1)
    
    1 row in set (0.00 sec)
    

    如果数据库不存在,则以 ER_BAD_DB_ERROR 拒绝该语句。如果用户没有运行该语句的必要权限,则会被拒绝,表示 ER_DBACCESS_DENIED_ERROR。If the database does not exist, the statement is rejected with ER_BAD_DB_ERROR. If the user does not have the necessary privileges to run the statement, it is rejected with ER_DBACCESS_DENIED_ERROR.

    FOR SCHEMA 与 FOR CONNECTION。FOR SCHEMA is not compatible with FOR CONNECTION.

EXPLAIN 需要执行该解释语句所需的权限。此外,EXPLAIN 还需要 SHOW VIEW 权限。EXPLAIN ... FOR CONNECTION 还需要 PROCESS 权限,如果指定的连接属于不同用户。EXPLAIN requires the same privileges required to execute the explained statement. Additionally, EXPLAIN also requires the SHOW VIEW privilege for any explained view. EXPLAIN ... FOR CONNECTION also requires the PROCESS privilege if the specified connection belongs to a different user.

explain_format 系统变量决定了 EXPLAIN 输出的格式,用于显示查询执行计划时。该变量可以取 FORMAT,并添加 DEFAULT,作为 TRADITIONAL词。以下示例使用了来自countryThe explain_format system variable determines the format of the output from EXPLAIN when used to display a query execution plan. This variable can take any of the values used with the FORMAT option, with the addition of DEFAULT as a synonym for TRADITIONAL. The following example uses the country table from the world database which can be obtained from MySQL: Other Downloads:

mysql> USE world; # Make world the current database
Database changed

检查explain_format,我们看到它为默认值,且EXPLAIN(没有 FORMAToption)因此使用传统的表格输出:Checking the value of explain_format, we see that it has the default value, and that EXPLAIN (with no FORMAT option) therefore uses the traditional tabular output:

mysql> SELECT @@explain_format;
+------------------+
| @@explain_format |
+------------------+
| TRADITIONAL      |
+------------------+
1 row in set (0.00 sec)

mysql> EXPLAIN SELECT Name FROM country WHERE Code Like 'A%';
+----+-------------+---------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table   | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra       |
+----+-------------+---------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | country | NULL       | range | PRIMARY       | PRIMARY | 12      | NULL |   17 |   100.00 | Using where |
+----+-------------+---------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

如果我们将explain_formatTREE然后重复运行相同的EXPLAIN语句,输出采用树状格式:If we set the value of explain_format to TREE, then rerun the same EXPLAIN statement, the output uses the tree-like format:

mysql> SET @@explain_format=TREE;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@explain_format;
+------------------+
| @@explain_format |
+------------------+
| TREE             |
+------------------+
1 row in set (0.00 sec)

mysql> EXPLAIN SELECT Name FROM country WHERE Code LIKE 'A%';
+--------------------------------------------------------------------------------------------------------------+
| EXPLAIN                                                                                                      |
+--------------------------------------------------------------------------------------------------------------+
| -> Filter: (country.`Code` like 'A%')  (cost=3.67 rows=17)
    -> Index range scan on country using PRIMARY over ('A' <= Code <= 'A????????')  (cost=3.67 rows=17)  |
+--------------------------------------------------------------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)

如前所述,FORMAT选项覆盖了该设置。使用EXPLAINAs stated previously, the FORMAT option overrides this setting. Executing the same EXPLAIN statement using FORMAT=JSON instead of FORMAT=TREE shows that this is the case:

mysql> EXPLAIN FORMAT=JSON SELECT Name FROM country WHERE Code LIKE 'A%';
+------------------------------------------------------------------------------+
| EXPLAIN                                                                      |
+------------------------------------------------------------------------------+
| {
  "query_block": {
    "select_id": 1,
    "cost_info": {
      "query_cost": "3.67"
    },
    "table": {
      "table_name": "country",
      "access_type": "range",
      "possible_keys": [
        "PRIMARY"
      ],
      "key": "PRIMARY",
      "used_key_parts": [
        "Code"
      ],
      "key_length": "12",
      "rows_examined_per_scan": 17,
      "rows_produced_per_join": 17,
      "filtered": "100.00",
      "cost_info": {
        "read_cost": "1.97",
        "eval_cost": "1.70",
        "prefix_cost": "3.67",
        "data_read_per_join": "16K"
      },
      "used_columns": [
        "Code",
        "Name"
      ],
      "attached_condition": "(`world`.`country`.`Code` like 'A%')"
    }
  }
}                                                                              |
+------------------------------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)

要返回默认输出EXPLAIN为表格格式,请将explain_formatTRADITIONAL或者,您也可以将其设置为DEFAULT效果相同,如此处所示:To return the default output of EXPLAIN to the tabular format, set explain_format to TRADITIONAL. Alternatively, you can set it to DEFAULT, which has the same effect, as shown here:

mysql> SET @@explain_format=DEFAULT;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@explain_format;
+------------------+
| @@explain_format |
+------------------+
| TRADITIONAL      |
+------------------+
1 row in set (0.00 sec)

MySQL 8.4 支持两种版本的 JSON 输出格式。版本 1 是线性格式,始终用于 MySQL 8.2 及更早版本;在 MySQL 8.4 中仍然是默认格式,并在本节前面已经显示的示例中使用。JSON 输出格式的版本 2 基于访问路径,旨在与 MySQL 优化器的未来版本兼容。您可以通过将服务器系统变量的值设置为explain_json_format_version切换到版本 2 格式,如下面针对前一个示例中使用的相同2语句所示:EXPLAIN使用版本 2 格式后,您可以通过将MySQL 8.4 supports two versions of the JSON output format. Version 1 is the linear format always used in MySQL 8.2 and earlier; this remains the default in MySQL 8.4, and is used in the examples already shown in this section. Version 2 of the JSON output format is based on access paths, and is intended to provide compatibility with future versions of the MySQL Optimizer. You can switch to the Version 2 format by setting the value of the explain_json_format_version server system variable to 2, as shown here for the same EXPLAIN statement used in the previous example:

mysql> SELECT @@explain_json_format_version;
+-------------------------------+
| @@explain_json_format_version |
+-------------------------------+
|                             1 |
+-------------------------------+
1 row in set (0.00 sec)

mysql> SET @@explain_json_format_version = 2;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@explain_json_format_version;
+-------------------------------+
| @@explain_json_format_version |
+-------------------------------+
|                             2 |
+-------------------------------+
1 row in set (0.00 sec)

mysql> EXPLAIN FORMAT=JSON SELECT Name FROM country WHERE Code LIKE 'A%';
+------------------------------------------------------------------------------+
| EXPLAIN                                                                      |
+------------------------------------------------------------------------------+
| {
  "query": "/* select#1 */ select `world`.`country`.`Name` AS `Name` from `world`.`country` where (`world`.`country`.`Code` like 'A%')",
  "inputs": [
    {
      "ranges": [
        "('A' <= Code <= 'A????????')"
      ],
      "covering": false,
      "operation": "Index range scan on country using PRIMARY over ('A' <= Code < 'A????????')",
      "index_name": "PRIMARY",
      "table_name": "country",
      "access_type": "index",
      "estimated_rows": 17.0,
      "index_access_type": "index_range_scan",
      "estimated_total_cost": 3.668778400708174
    }
  ],
  "condition": "(country.`Code` like 'A%')",
  "operation": "Filter: (country.`Code` like 'A%')",
  "access_type": "filter",
  "estimated_rows": 17.0,
  "estimated_total_cost": 3.668778400708174
}                                                                              |
+------------------------------------------------------------------------------+

重新设置为EXPLAIN FORMAT=JSON(默认值)来使所有后续explain_json_format_version语句的 JSON 输出返回到版本 1 格式。1通过After using the Version 2 format, you can cause the JSON output from all subsequent EXPLAIN FORMAT=JSON statements to revert to the Version 1 format by setting explain_json_format_version back to 1 (the default).

explain_json_format_version决定了所有使用 JSON 输出格式的 EXPLAIN 语句所采用的版本,是因为给定的 EXPLAIN 语句包含显式的 FORMAT=JSON 选项,还是因为 explain_format系统变量设置为 JSON 格式。The value of explain_json_format_version determines the version of the JSON output format employed by all EXPLAIN statements which use it, whether the JSON format is used because a given EXPLAIN statement includes an explicit FORMAT=JSON option, or because the JSON format is used automatically due to the explain_format system variable being set to JSON.

借助 EXPLAIN,您可以查看应在哪些表上添加索引,以便语句通过使用索引查找行时执行得更快。您还可以使用 EXPLAIN 来检查优化器是否以最佳顺序连接表。要向优化器提示使用与 SELECT 语句中表的命名顺序相对应的连接顺序,请在语句开头使用 SELECT STRAIGHT_JOIN,而不仅仅是 SELECT。(参见 第 15.2.13 节,“SELECT 语句”。)With the help of EXPLAIN, you can see where you should add indexes to tables so that the statement executes faster by using indexes to find rows. You can also use EXPLAIN to check whether the optimizer joins the tables in an optimal order. To give a hint to the optimizer to use a join order corresponding to the order in which the tables are named in a SELECT statement, begin the statement with SELECT STRAIGHT_JOIN rather than just SELECT. (See Section 15.2.13, “SELECT Statement”.)

优化器跟踪有时可能提供与 EXPLAIN 补充的信息。然而,优化器跟踪的格式和内容可能会随着版本的不同而发生变化。有关详细信息,请参见 第 10.15 节,“跟踪优化器”。The optimizer trace may sometimes provide information complementary to that of EXPLAIN. However, the optimizer trace format and content are subject to change between versions. For details, see Section 10.15, “Tracing the Optimizer”.

如果您遇到索引未被使用的问题,而您认为它们应该被使用,请运行 ANALYZE TABLE 来更新表统计信息,例如键的基数,这些信息可能会影响优化器的选择。请参见 第 15.7.3.1 节,“ANALYZE TABLE 语句”。If you have a problem with indexes not being used when you believe that they should be, run ANALYZE TABLE to update table statistics, such as cardinality of keys, that can affect the choices the optimizer makes. See Section 15.7.3.1, “ANALYZE TABLE Statement”.

Note

MySQL Workbench 具有可视化解释功能,可以提供 EXPLAIN 输出的可视化表示。请参阅 教程:使用 Explain 提高查询性能。MySQL Workbench has a Visual Explain capability that provides a visual representation of EXPLAIN output. See Tutorial: Using Explain to Improve Query Performance.

使用 EXPLAIN ANALYZE 获取信息Obtaining Information with EXPLAIN ANALYZE

EXPLAIN ANALYZE 执行一个语句,并生成 EXPLAIN 输出,同时提供有关优化器预期与实际执行如何匹配的时间和其他基于迭代器的信息。对于每个迭代器,提供以下信息:EXPLAIN ANALYZE runs a statement and produces EXPLAIN output along with timing and additional, iterator-based, information about how the optimizer's expectations matched the actual execution. For each iterator, the following information is provided:

  • 估计执行成本Estimated execution cost

    (某些迭代器不在成本模型的考虑范围内,因此未包含在估计中。)(Some iterators are not accounted for by the cost model, and so are not included in the estimate.)

  • 估计返回的行数Estimated number of returned rows

  • 返回第一行的时间Time to return first row

  • 执行该迭代器所花费的时间(包括子迭代器,但不包括父迭代器),以毫秒为单位。Time spent executing this iterator (including child iterators, but not parent iterators), in milliseconds.

    (当存在多个循环时,该数字显示每次循环的平均时间。)(When there are multiple loops, this figure shows the average time per loop.)

  • 迭代器返回的行数Number of rows returned by the iterator

  • 循环次数Number of loops

查询执行信息以 TREE 输出格式显示,其中节点表示迭代器。EXPLAIN ANALYZE 总是使用 TREE 输出格式。可以通过 FORMAT=TREE 显式指定;不支持 TREE 以外的格式。The query execution information is displayed using the TREE output format, in which nodes represent iterators. EXPLAIN ANALYZE always uses the TREE output format. This can optionally be specified explicitly using FORMAT=TREE; formats other than TREE remain unsupported.

EXPLAIN ANALYZE 可用于 SELECT 语句、多表 UPDATE 和 DELETE 语句,以及 TABLE 语句。EXPLAIN ANALYZE can be used with SELECT statements, multi-table UPDATE and DELETE statements, and TABLE statements.

您可以使用 KILL QUERY 或 CTRL-C 终止此语句。You can terminate this statement using KILL QUERY or CTRL-C.

EXPLAIN ANALYZE 不能与 FOR CONNECTION 一起使用。EXPLAIN ANALYZE cannot be used with FOR CONNECTION.

示例输出:Example output:

mysql> EXPLAIN ANALYZE SELECT * FROM t1 JOIN t2 ON (t1.c1 = t2.c2)\G
*************************** 1. row ***************************
EXPLAIN: -> Inner hash join (t2.c2 = t1.c1)  (cost=3.5 rows=5) 
(actual time=0.121..0.131 rows=1 loops=1) 
    -> Table scan on t2  (cost=0.07 rows=5) 
(actual time=0.0126..0.0221 rows=5 loops=1) 
    -> Hash
        -> Table scan on t1  (cost=0.75 rows=5) 
(actual time=0.0372..0.0534 rows=5 loops=1)

mysql> EXPLAIN ANALYZE SELECT * FROM t3 WHERE i > 8\G
*************************** 1. row ***************************
EXPLAIN: -> Filter: (t3.i > 8)  (cost=0.75 rows=1.67) 
(actual time=0.0168..0.0182 rows=1 loops=1)
    -> Table scan on t3  (cost=0.75 rows=5) 
(actual time=0.015..0.0167 rows=5 loops=1)

mysql> EXPLAIN ANALYZE FORMAT=TREE SELECT * FROM t3 WHERE pk > 17\G
*************************** 1. row ***************************
EXPLAIN: -> Filter: (t3.pk > 17)  (cost=0.91 rows=2) 
(actual time=0.0334..0.042 rows=2 loops=1)
    -> Index range scan on t3 using PRIMARY over (17 < pk)  
(cost=0.91 rows=2) (actual time=0.0306..0.0384 rows=2 loops=1)

示例输出中使用的表是通过此处显示的语句创建的:The tables used in the example output were created by the statements shown here:

CREATE TABLE t1 (
    c1 INTEGER DEFAULT NULL,
    c2 INTEGER DEFAULT NULL
);

CREATE TABLE t2 (
    c1 INTEGER DEFAULT NULL,
    c2 INTEGER DEFAULT NULL
);

CREATE TABLE t3 (
    pk INTEGER NOT NULL PRIMARY KEY,
    i INTEGER DEFAULT NULL
);

此语句输出中显示的 actual time 的值以毫秒为单位。Values shown for actual time in the output of this statement are expressed in milliseconds.

explain_format 对 EXPLAIN ANALYZE 有以下影响:explain_format has the following effects on EXPLAIN ANALYZE:

  • 如果该变量的值为 TRADITIONAL 或 TREE(或同义词 DEFAULTEXPLAIN ANALYZE 使用 TREE 格式。这确保该语句继续使用 TREE 格式默认,就像引入 explain_formatIf the value of this variable is TRADITIONAL or TREE (or the synonym DEFAULT), EXPLAIN ANALYZE uses the TREE format. This ensures that this statement continues to use the TREE format by default, as it did prior to the introduction of explain_format.

  • 一样。如果 explain_format是 JSONEXPLAIN ANALYZE 会返回错误,除非语句中指定为 FORMAT=TREE。这是因为 EXPLAIN ANALYZE 只支持 TREE输出格式。If the value of explain_format is JSON, EXPLAIN ANALYZE returns an error unless FORMAT=TREE is specified as part of the statement. This is due to the fact that EXPLAIN ANALYZE supports only the TREE output format.

我们在这里展示了第二点描述的行为,重复使用了前一个示例中的最后一个 EXPLAIN ANALYZE 语句:We illustrate the behavior described in the second point here, re-using the last EXPLAIN ANALYZE statement from the previous example:

mysql> SET @@explain_format=JSON;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@explain_format;
+------------------+
| @@explain_format |
+------------------+
| JSON             |
+------------------+
1 row in set (0.00 sec)

mysql> EXPLAIN ANALYZE SELECT * FROM t3 WHERE pk > 17\G
ERROR 1235 (42000): This version of MySQL doesn't yet support 'EXPLAIN ANALYZE with JSON format'

mysql> EXPLAIN ANALYZE FORMAT=TRADITIONAL SELECT * FROM t3 WHERE pk > 17\G
ERROR 1235 (42000): This version of MySQL doesn't yet support 'EXPLAIN ANALYZE with TRADITIONAL format'

mysql> EXPLAIN ANALYZE FORMAT=TREE SELECT * FROM t3 WHERE pk > 17\G
*************************** 1. row ***************************
EXPLAIN: -> Filter: (t3.pk > 17)  (cost=1.26 rows=5)
(actual time=0.013..0.016 rows=5 loops=1)
    -> Index range scan on t3 using PRIMARY  (cost=1.26 rows=5)
(actual time=0.012..0.014 rows=5 loops=1)

使用 FORMAT=TRADITIONAL 或 FORMAT=JSON 搭配 EXPLAIN ANALYZE 总是会触发错误,无论 explain_format。Using FORMAT=TRADITIONAL or FORMAT=JSON with EXPLAIN ANALYZE always raises an error, regardless of the value of explain_format.

在 MySQL 8.4 中,输出EXPLAIN ANALYZE和EXPLAIN FORMAT=TREE按照以下规则进行格式化:In MySQL 8.4, numbers in the output of EXPLAIN ANALYZE and EXPLAIN FORMAT=TREE are formatted according to the following rules:

  • 为 0.001-99999.5 的数字以十进制数字打印。Numbers in the range 0.001-999999.5 are printed as decimal numbers.

    小于 1000 的十进制数字有三个有效位;其余数字为四个、五个或六个。Decimal numbers less than 1000 have three significant digits; the remainder have four, five, or six.

  • 超出 0.001-999999.5 范围的数字以工程格式打印。此类数值的例子有 1.23e+9 和 934e-6。Numbers outside the range 0.001-999999.5 are printed in engineering format. Examples of such values are 1.23e+9 and 934e-6.

  • 不打印尾部零。例如,我们打印 2.3,而不是 2.30;1.2e+6,而不是 1.20e+6。No trailing zeros are printed. For example, we print 2.3 rather than 2.30, and 1.2e+6 rather than 1.20e+6.

  • 小于 1e-12会打印为 0。Numbers less than 1e-12 are printed as 0.