EXPLAIN 语句提供有关 MySQL 如何执行语句的信息。EXPLAIN 可与 SELECT、DELETE、INSERT、REPLACE 和 UPDATE 语句一起使用。The EXPLAIN statement provides
information about how MySQL executes statements.
EXPLAIN works with
SELECT,
DELETE,
INSERT,
REPLACE, and
UPDATE statements.
EXPLAIN 返回 SELECT 语句中每个使用的表的信息行。它按 MySQL 在处理语句时读取表的顺序列出输出中的表。这意味着 MySQL 首先从第一个表读取一行,然后在第二个表中找到匹配的行,再在第三个表中找到匹配的行,依此类推。当所有表都被处理完时,MySQL 输出所选列,并回溯表列表,直到找到一个尚有匹配行的表。从这个表中读取下一行,接着在下一个表中继续此过程。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. This means that MySQL reads a
row from the first table, then finds a matching row in the
second table, and then in 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.
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 生成的输出列。后续章节提供了关于 type 和 Extra 列的更多信息。This section describes the output columns produced by
EXPLAIN. Later sections provide
additional information about the
type
and
Extra
columns.
来自 EXPLAIN 的每一行输出都提供有关一个表的信息。每行包含 表 10.1,“EXPLAIN 输出列” 中汇总的值,并在表格之后进行了更详细的描述。表格的第一列显示列名;第二列提供当使用 FORMAT=JSON 时输出中显示的等效属性名称。Each output row from EXPLAIN
provides information about one table. Each row contains the
values summarized in
Table 10.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.
表 10.1 EXPLAIN 输出列Table 10.1 EXPLAIN Output Columns
| 列Column | JSON 名称JSON Name | 意义Meaning |
|---|---|---|
id |
select_id |
SELECT 标识符The SELECT identifier |
select_type |
无None | SELECT 类型The SELECT type |
tabletable |
table_nametable_name |
输出行的表格The table for the output row |
partitionspartitions |
partitionspartitions |
匹配的分区The matching partitions |
typetype |
access_typeaccess_type |
连接类型The join type |
possible_keys |
possible_keys |
可选择的可能索引The possible indexes to choose |
keykey |
keykey |
实际选择的索引The index actually chosen |
key_len |
key_length |
所选密钥的长度The length of the chosen key |
refref |
refref |
与索引比较的列The columns compared to the index |
rowsrows |
rowsrows |
要检查的行数估计Estimate of rows to be examined |
filteredfiltered |
filteredfiltered |
按表条件过滤的行百分比Percentage of rows filtered by table condition |
ExtraExtra |
无None | 附加信息Additional information |
JSON 属性为 NULL 的不会显示在 JSON 格式的 EXPLAIN 输出中。JSON properties which are NULL are not
displayed in JSON-formatted EXPLAIN
output.
id(JSON 名称:select_id)id(JSON name:select_id)SELECT标识符。它是查询中SELECT的顺序编号。如果该行指向其他行的联合结果,则该值可以为NULL。在这种情况下,table列显示类似<union的值,以表明该行指向M,N>id值为M和N的行的联合结果。TheSELECTidentifier. This is the sequential number of theSELECTwithin the query. The value can beNULLif the row refers to the union result of other rows. In this case, thetablecolumn shows a value like<unionto indicate that the row refers to the union of the rows withM,N>idvalues ofMandN.select_type(JSON 名称:无)select_type(JSON name: none)SELECT的类型,可以是下表中显示的任意一种。以 JSON 格式的EXPLAIN会将SELECT类型作为query_block的属性暴露出来,除非它是SIMPLE或PRIMARY。表中也显示了 JSON 名称(如适用)。The type ofSELECT, which can be any of those shown in the following table. A JSON-formattedEXPLAINexposes theSELECTtype as a property of aquery_block, unless it isSIMPLEorPRIMARY. The JSON names (where applicable) are also shown in the table.select_type值select_typeValueJSON 名称JSON Name 意义Meaning SIMPLESIMPLE无None 简单 SELECT(不使用UNION或子查询)SimpleSELECT(not usingUNIONor subqueries)PRIMARYPRIMARY无None 最外层的 SELECTOutermostSELECTUNIONUNION无None 第二次或之后 SELECT语句在一个UNIONSecond or laterSELECTstatement in aUNIONDEPENDENT UNIONDEPENDENT UNIONdependent(true)第二个或之后的 SELECT语句在UNION中,依赖外部查询Second or laterSELECTstatement in aUNION, dependent on outer queryUNION RESULTUNION RESULTunion_resultunion_resultUNION的结果。Result of aUNION.SUBQUERYSUBQUERY无None 子查询中的第一个 SELECTFirstSELECTin subqueryDEPENDENT SUBQUERYdependent(true)子查询中的第一个 SELECT,依赖于外部查询FirstSELECTin subquery, dependent on outer queryDERIVED无None 派生表Derived table DEPENDENT DERIVEDDEPENDENT DERIVEDdependent(true)依赖于另一张表的派生表Derived table dependent on another table MATERIALIZEDMATERIALIZEDmaterialized_from_subquerymaterialized_from_subquery物化子查询Materialized subquery UNCACHEABLE SUBQUERYUNCACHEABLE SUBQUERYcacheable(false)cacheable(false)一个其结果不能被缓存且必须为外部查询的每一行重新计算的子查询A subquery for which the result cannot be cached and must be re-evaluated for each row of the outer query UNCACHEABLE UNIONUNCACHEABLE UNIONcacheable(false)cacheable(false)第二次或之后的选择在一个 UNION属于不可缓存子查询的UNCACHEABLE SUBQUERY)The second or later select in aUNIONthat belongs to an uncacheable subquery (seeUNCACHEABLE SUBQUERY)DEPENDENT通常表示使用了相关子查询。参见 第 15.2.15.7 节,“相关子查询”。DEPENDENTtypically signifies the use of a correlated subquery. See Section 15.2.15.7, “Correlated Subqueries”.DEPENDENT SUBQUERY的评估方式不同于UNCACHEABLE SUBQUERY的评估方式。对于DEPENDENT SUBQUERY,子查询仅在其外部上下文变量的不同值集合下重新评估一次。对于UNCACHEABLE SUBQUERY,子查询会针对外部上下文的每一行重新评估。DEPENDENT SUBQUERYevaluation differs fromUNCACHEABLE SUBQUERYevaluation. ForDEPENDENT SUBQUERY, the subquery is re-evaluated only once for each set of different values of the variables from its outer context. ForUNCACHEABLE SUBQUERY, the subquery is re-evaluated for each row of the outer context.当您在
EXPLAIN中指定FORMAT=JSON时,输出中没有与select_type直接对应的单个属性;query_block属性对应于给定的SELECT。与刚刚显示的大多数SELECT子查询类型相对应的属性是可用的(例如materialized_from_subquery对应MATERIALIZED),并在适当的时候显示。对于SIMPLE或PRIMARY没有 JSON 对应项。When you specifyFORMAT=JSONwithEXPLAIN, the output has no single property directly equivalent toselect_type; thequery_blockproperty corresponds to a givenSELECT. Properties equivalent to most of theSELECTsubquery types just shown are available (an example beingmaterialized_from_subqueryforMATERIALIZED), and are displayed when appropriate. There are no JSON equivalents forSIMPLEorPRIMARY.非
SELECT语句的select_type值显示受影响表的语句类型。例如,对于DELETE语句,select_type的值为DELETE。Theselect_typevalue for non-SELECTstatements displays the statement type for affected tables. For example,select_typeisDELETEforDELETEstatements.table(JSON 名称:table_name)table(JSON name:table_name)输出行所指的表的名称。这也可以是以下值之一:The name of the table to which the row of output refers. This can also be one of the following values:
<union:该行指的是M,N>id值为M和N的行的并集。<union: The row refers to the union of the rows withM,N>idvalues ofMandN.<derived:该行指的是N>id值为N的行的派生表结果。例如,派生表可能来源于FROM子句中的子查询。<derived: The row refers to the derived table result for the row with anN>idvalue ofN. A derived table may result, for example, from a subquery in theFROMclause.<subquery:该行指的是具有N>id值为N的行的物化子查询结果。参见 第 10.2.2.2 节,“使用物化优化子查询”。<subquery: The row refers to the result of a materialized subquery for the row with anN>idvalue ofN. See Section 10.2.2.2, “Optimizing Subqueries with Materialization”.
partitions(JSON 名称:partitions)partitions(JSON name:partitions)查询会匹配记录的分区。对于非分区表,该值为
NULL。参见 第 26.3.5 节,“获取分区信息”。The partitions from which records would be matched by the query. The value isNULLfor nonpartitioned tables. See Section 26.3.5, “Obtaining Information About Partitions”.type(JSON 名称:access_type)type(JSON name:access_type)连接类型。有关不同类型的描述,请参见
EXPLAIN连接类型。The join type. For descriptions of the different types, seeEXPLAINJoin Types.possible_keys(JSON 名称:possible_keys)possible_keys(JSON name:possible_keys)possible_keys列表示 MySQL 可以选择用来查找该表中行的索引。请注意,这一列与输出中显示的表顺序完全无关,输出顺序来自EXPLAIN。这意味着possible_keys中的某些索引在实际生成的表顺序下可能无法使用。Thepossible_keyscolumn indicates the indexes from which MySQL can choose to find the rows in this table. Note that this column is totally independent of the order of the tables as displayed in the output fromEXPLAIN. That means that some of the keys inpossible_keysmight not be usable in practice with the generated table order.如果该列为
NULL(或在 JSON 格式输出中未定义),则没有相关索引。在这种情况下,你可以通过检查WHERE子句是否涉及适合索引的某些列来提高查询性能。如果是这样,请创建适当的索引,然后再次使用EXPLAIN检查查询。参见 第 15.1.9 节,“ALTER TABLE 语句”。If this column isNULL(or undefined in JSON-formatted output), there are no relevant indexes. In this case, you may be able to improve the performance of your query by examining theWHEREclause to check whether it refers to some column or columns that would be suitable for indexing. If so, create an appropriate index and check the query withEXPLAINagain. See Section 15.1.9, “ALTER TABLE Statement”.要查看表有哪些索引,请使用
SHOW INDEX FROM tbl_name。To see what indexes a table has, useSHOW INDEX FROM.tbl_namekey(JSON 名称:key)key(JSON name:key)key列表示 MySQL 实际决定使用的键(索引)。如果 MySQL 决定使用possible_keys中的某个索引来查找行,则该索引会列为 key 值。Thekeycolumn indicates the key (index) that MySQL actually decided to use. If MySQL decides to use one of thepossible_keysindexes to look up rows, that index is listed as the key value.key可能会命名一个不在possible_keys值中的索引。如果possible_keys中没有适合查找行的索引,但查询选择的所有列都属于其他索引的列,就会发生这种情况。也就是说,命名的索引覆盖了所选列,因此虽然它没有用于确定要检索的行,但索引扫描比数据行扫描更高效。It is possible thatkeymay name an index that is not present in thepossible_keysvalue. This can happen if none of thepossible_keysindexes are suitable for looking up rows, but all the columns selected by the query are columns of some other index. That is, the named index covers the selected columns, so although it is not used to determine which rows to retrieve, an index scan is more efficient than a data row scan.对于
InnoDB,即使查询也选择了主键,二级索引仍可能涵盖所选列,因为InnoDB在每个二级索引中存储了主键值。如果key为NULL,则 MySQL 未找到可用于更高效执行查询的索引。ForInnoDB, a secondary index might cover the selected columns even if the query also selects the primary key becauseInnoDBstores the primary key value with each secondary index. IfkeyisNULL, MySQL found no index to use for executing the query more efficiently.要强制 MySQL 使用或忽略
possible_keys列中列出的索引,请在查询中使用FORCE INDEX、USE INDEX或IGNORE INDEX。请参阅 第 10.9.4 节,“索引提示”。To force MySQL to use or ignore an index listed in thepossible_keyscolumn, useFORCE INDEX,USE INDEX, orIGNORE INDEXin your query. See Section 10.9.4, “Index Hints”.对于
MyISAM表,运行ANALYZE TABLE可以帮助优化器选择更好的索引。对于MyISAM表,myisamchk --analyze 也具有相同的作用。参见 第 15.7.3.1 节,“ANALYZE TABLE 语句” 和 第 9.6 节,“MyISAM 表维护和崩溃恢复”。ForMyISAMtables, runningANALYZE TABLEhelps the optimizer choose better indexes. ForMyISAMtables, myisamchk --analyze does the same. See Section 15.7.3.1, “ANALYZE TABLE Statement”, and Section 9.6, “MyISAM Table Maintenance and Crash Recovery”.key_len(JSON 名称:key_length)key_len(JSON name:key_length)key_len列表示 MySQL 决定使用的键长度。key_len的值使您能够确定 MySQL 实际使用了多部分键中的多少部分。如果key列显示NULL,则key_len列也会显示NULL。Thekey_lencolumn indicates the length of the key that MySQL decided to use. The value ofkey_lenenables you to determine how many parts of a multiple-part key MySQL actually uses. If thekeycolumn saysNULL, thekey_lencolumn also saysNULL.由于键的存储格式,可为
NULL的列的键长度比NOT NULL列多一。Due to the key storage format, the key length is one greater for a column that can beNULLthan for aNOT NULLcolumn.ref(JSON 名称:ref)ref(JSON name:ref)ref列显示与key列中命名的索引进行比较以从表中选择行的列或常量。Therefcolumn shows which columns or constants are compared to the index named in thekeycolumn to select rows from the table.如果值是
func,则使用的值是某个函数的结果。要查看是哪一个函数,请在EXPLAIN之后使用SHOW WARNINGS查看扩展的EXPLAIN输出。这个函数实际上可能是一个算术运算符等操作符。If the value isfunc, the value used is the result of some function. To see which function, useSHOW WARNINGSfollowingEXPLAINto see the extendedEXPLAINoutput. The function might actually be an operator such as an arithmetic operator.rows(JSON 名称:rows)rows(JSON name:rows)rows列表示 MySQL 认为必须检查的行数,以执行查询。Therowscolumn indicates the number of rows MySQL believes it must examine to execute the query.对于
InnoDB表,这个数字是一个估计值,可能并不总是准确的。ForInnoDBtables, this number is an estimate, and may not always be exact.filtered(JSON 名称:filtered)filtered(JSON name:filtered)filtered列表示按表条件过滤的表行的估计百分比。最大值为 100,表示未对行进行任何过滤。从 100 开始下降的值表示过滤量增加。rows显示估算检查的行数,而rows×filtered显示将与下一个表连接的行数。例如,如果rows为 1000 且filtered为 50.00 (50%),则要与下一个表连接的行数为 1000 × 50% = 500。Thefilteredcolumn indicates an estimated percentage of table rows that are filtered by the table condition. The maximum value is 100, which means no filtering of rows occurred. Values decreasing from 100 indicate increasing amounts of filtering.rowsshows the estimated number of rows examined androws×filteredshows the number of rows that are joined with the following table. For example, ifrowsis 1000 andfilteredis 50.00 (50%), the number of rows to be joined with the following table is 1000 × 50% = 500.Extra(JSON 名称:none)Extra(JSON name: none)此列包含有关 MySQL 如何解析查询的附加信息。有关不同值的描述,请参见
EXPLAIN附加信息。This column contains additional information about how MySQL resolves the query. For descriptions of the different values, seeEXPLAINExtra Information.没有与
Extra列对应的单一 JSON 属性;但是,该列中可能出现的值会以 JSON 属性的形式显示,或作为message属性的文本。There is no single JSON property corresponding to theExtracolumn; however, values that can occur in this column are exposed as JSON properties, or as the text of themessageproperty.
该type的列EXPLAIN输出描述了表是如何连接的。在 JSON 格式的输出中,这些作为access_type属性。以下列表描述了连接类型,按从最好到最差的顺序排列: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:
该表只有一行(= 系统表)。这是
const连接类型的特殊情况。The table has only one row (= system table). This is a special case of theconstjoin type.该表最多只有一条匹配的行,这条行在查询开始时就被读取。因为只有一行,这行中的列值可以被优化器的其余部分视为常量。
const表非常快,因为它们只读取一次。The table has at most one matching row, which is read at the start of the query. Because there is only one row, values from the column in this row can be regarded as constants by the rest of the optimizer.consttables are very fast because they are read only once.const用于当你将PRIMARY KEY或UNIQUE索引的所有部分与常量值进行比较时。在以下查询中,tbl_name可以作为const表使用:constis used when you compare all parts of aPRIMARY KEYorUNIQUEindex to constant values. In the following queries,tbl_namecan be used as aconsttable:SELECT * FROM
tbl_nameWHEREprimary_key=1; SELECT * FROMtbl_nameWHEREprimary_key_part1=1 ANDprimary_key_part2=2;对于前面表的每种行组合,将从此表读取一行。除了
system和const类型之外,这是可能的最佳连接类型。当连接使用索引的所有部分并且该索引是PRIMARY KEY或UNIQUE NOT NULL索引时,将使用此类型。One row is read from this table for each combination of rows from the previous tables. Other than thesystemandconsttypes, this is the best possible join type. It is used when all parts of an index are used by the join and the index is aPRIMARY KEYorUNIQUE NOT NULLindex.eq_ref可以用于通过=操作符进行比较的索引列。比较值可以是常量,也可以是使用先前读取的表中的列的表达式。在以下示例中,MySQL 可以使用eq_ref连接来处理ref_table:eq_refcan be used for indexed columns that are compared using the=operator. The comparison value can be a constant or an expression that uses columns from tables that are read before this table. In the following examples, MySQL can use aneq_refjoin to processref_table:SELECT * FROM
ref_table,other_tableWHEREref_table.key_column=other_table.column; SELECT * FROMref_table,other_tableWHEREref_table.key_column_part1=other_table.columnANDref_table.key_column_part2=1;对于来自前面表的每一行组合,将从此表中读取所有具有匹配索引值的行。如果连接仅使用键的最左前缀,或者该键不是
PRIMARY KEY或UNIQUE索引,则使用ref(换句话说,如果连接无法根据键值选择单行)。如果使用的键仅匹配少量行,这是一个好的连接类型。All rows with matching index values are read from this table for each combination of rows from the previous tables.refis used if the join uses only a leftmost prefix of the key or if the key is not aPRIMARY KEYorUNIQUEindex (in other words, if the join cannot select a single row based on the key value). If the key that is used matches only a few rows, this is a good join type.ref可以用于通过=或<=>操作符进行比较的索引列。在以下示例中,MySQL 可以使用ref联接来处理ref_table:refcan be used for indexed columns that are compared using the=or<=>operator. In the following examples, MySQL can use arefjoin to processref_table:SELECT * FROM
ref_tableWHEREkey_column=expr; SELECT * FROMref_table,other_tableWHEREref_table.key_column=other_table.column; SELECT * FROMref_table,other_tableWHEREref_table.key_column_part1=other_table.columnANDref_table.key_column_part2=1;该联接是使用
FULLTEXT索引执行的。The join is performed using aFULLTEXTindex.这种连接类型类似于
ref,但额外地,MySQL 会对包含NULL值的行进行一次额外搜索。这种连接类型的优化最常用于解析子查询。在以下示例中,MySQL 可以使用ref_or_null连接来处理ref_table:This join type is likeref, but with the addition that MySQL does an extra search for rows that containNULLvalues. This join type optimization is used most often in resolving subqueries. In the following examples, MySQL can use aref_or_nulljoin to processref_table:SELECT * FROM
ref_tableWHEREkey_column=exprORkey_columnIS NULL;参见 第 10.2.1.15 节,“IS NULL 优化”。See Section 10.2.1.15, “IS NULL Optimization”.
此连接类型表示使用了索引合并(Index Merge)优化。在这种情况下,输出行中的
key列包含使用的索引列表,key_len包含所使用索引的最长键部分列表。更多信息,请参见 第 10.2.1.3 节,“索引合并优化”。This join type indicates that the Index Merge optimization is used. In this case, thekeycolumn in the output row contains a list of indexes used, andkey_lencontains a list of the longest key parts for the indexes used. For more information, see Section 10.2.1.3, “Index Merge Optimization”.此类型在某些形式如下的
IN子查询中替代eq_ref:This type replaceseq_reffor someINsubqueries of the following form:valueIN (SELECTprimary_keyFROMsingle_tableWHEREsome_expr)unique_subquery只是一个索引查找函数,用来完全替代子查询,以提高效率。unique_subqueryis just an index lookup function that replaces the subquery completely for better efficiency.这种连接类型类似于
unique_subquery。它替代了IN子查询,但它适用于以下形式子查询中的非唯一索引:This join type is similar tounique_subquery. It replacesINsubqueries, but it works for nonunique indexes in subqueries of the following form:valueIN (SELECTkey_columnFROMsingle_tableWHEREsome_expr)只有位于给定范围内的行会被检索,使用索引来选择这些行。输出行中的
key列表示使用的是哪个索引。key_len包含使用的最长键部分。对于这种类型,ref列为NULL。Only rows that are in a given range are retrieved, using an index to select the rows. Thekeycolumn in the output row indicates which index is used. Thekey_lencontains the longest key part that was used. Therefcolumn isNULLfor this type.range可以在键列与常量使用任何=、<>、>、>=、<、<=、IS NULL、<=>、BETWEEN、LIKE或IN()运算符时使用:rangecan be used when a key column is compared to a constant using any of the=,<>,>,>=,<,<=,IS NULL,<=>,BETWEEN,LIKE, orIN()operators:SELECT * FROM
tbl_nameWHEREkey_column= 10; SELECT * FROMtbl_nameWHEREkey_columnBETWEEN 10 and 20; SELECT * FROMtbl_nameWHEREkey_columnIN (10,20,30); SELECT * FROMtbl_nameWHEREkey_part1= 10 ANDkey_part2IN (10,20,30);index连接类型与ALL相同,只是扫描的是索引树。出现这种情况有两种方式:Theindexjoin type is the same asALL, except that the index tree is scanned. This occurs two ways:如果索引是查询的覆盖索引,并且可以用于满足表中所需的所有数据,则只扫描索引树。在这种情况下,
Extra列会显示Using index。仅索引扫描通常比ALL更快,因为索引的大小通常小于表数据。If the index is a covering index for the queries and can be used to satisfy all data required from the table, only the index tree is scanned. In this case, theExtracolumn saysUsing index. An index-only scan usually is faster thanALLbecause the size of the index usually is smaller than the table data.使用索引读取按索引顺序查找数据行来执行全表扫描。
Extra列中不会显示Uses index。A full table scan is performed using reads from the index to look up data rows in index order.Uses indexdoes not appear in theExtracolumn.
当查询只使用属于单个索引的列时,MySQL 可以使用这种连接类型。MySQL can use this join type when the query uses only columns that are part of a single index.
对于来自前面表的每一行组合,都会进行全表扫描。如果该表是未标记
const的第一个表,这通常不是好事,在其他所有情况下一般是非常糟糕的。通常,你可以通过添加索引来避免ALL,这些索引可以基于常量值或来自前面表的列值检索表中的行。A full table scan is done for each combination of rows from the previous tables. This is normally not good if the table is the first table not markedconst, and usually very bad in all other cases. Normally, you can avoidALLby adding indexes that enable row retrieval from the table based on constant values or column values from earlier tables.
该Extra的列EXPLAIN输出包含有关 MySQL 如何解析查询的附加信息。以下列表解释了此列中可能出现的值。每一项还指明了 JSON 格式输出中哪个属性显示该Extra值。对于其中的一些,有特定的属性。其他的则显示为message属性的文本。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.
如果你想让查询尽可能快,请注意 Extra 列值中的 Using
filesort 和 Using temporary,或者在 JSON 格式的 EXPLAIN 输出中,注意 using_filesort 和 using_temporary_table 属性为 true。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.
Backward index scan(JSON:backward_index_scan)Backward index scan(JSON:backward_index_scan)优化器能够在
InnoDB表上使用降序索引。与Using index一起显示。更多信息,请参见 第 10.3.13 节,“降序索引”。The optimizer is able to use a descending index on anInnoDBtable. Shown together withUsing index. For more information, see Section 10.3.13, “Descending Indexes”.Child of 'table' pushed join@1(JSON:message文本)Child of '(JSON:table' pushed join@1messagetext)当该表作为
table的子表在可以下推到 NDB 内核的连接中引用时才适用。仅在启用下推连接的 NDB 集群中适用。有关更多信息和示例,请参阅ndb_join_pushdown服务器系统变量的说明。This table is referenced as the child oftablein a join that can be pushed down to the NDB kernel. Applies only in NDB Cluster, when pushed-down joins are enabled. See the description of thendb_join_pushdownserver system variable for more information and examples.const row not found(JSON 属性:const_row_not_found)const row not found(JSON property:const_row_not_found)对于如
SELECT ... FROM tbl_name的查询,该表为空。For a query such asSELECT ... FROM, the table was empty.tbl_nameDeleting all rows(JSON 属性:message)Deleting all rows(JSON property:message)对于
DELETE,一些存储引擎(例如MyISAM)支持一种处理方法,可以简单快速地删除所有表行。如果引擎使用此优化,则会显示此Extra值。ForDELETE, some storage engines (such asMyISAM) support a handler method that removes all table rows in a simple and fast way. ThisExtravalue is displayed if the engine uses this optimization.Distinct(JSON 属性:distinct)Distinct(JSON property:distinct)MySQL 正在查找不同的值,因此在找到第一个匹配的行之后,它会停止搜索当前行组合的更多行。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((JSON 属性:tbl_name)first_match)FirstMatch((JSON property:tbl_name)first_match)半连接 FirstMatch 连接捷径策略用于
tbl_name。The semijoin FirstMatch join shortcutting strategy is used fortbl_name.Full scan on NULL key(JSON 属性:message)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 属性:message)Impossible HAVING(JSON property:message)HAVING子句总是为假,无法选择任何行。TheHAVINGclause is always false and cannot select any rows.Impossible WHERE(JSON 属性:message)Impossible WHERE(JSON property:message)WHERE子句总是为假,无法选择任何行。TheWHEREclause is always false and cannot select any rows.Impossible WHERE noticed after reading const tables(JSON 属性:message)Impossible WHERE noticed after reading const tables(JSON property:message)MySQL 已经读取了所有
const(和system)表,并注意到WHERE子句总是为假。MySQL has read allconst(andsystem) tables and notice that theWHEREclause is always false.LooseScan((JSON 属性:m..n)message)LooseScan((JSON property:m..n)message)使用半连接 LooseScan 策略。
m和n是关键零件编号。The semijoin LooseScan strategy is used.mandnare key part numbers.No matching min/max row(JSON 属性:message)No matching min/max row(JSON property:message)没有行满足查询条件,例如
SELECT MIN(...) FROM ... WHERE condition的查询条件。No row satisfies the condition for a query such asSELECT MIN(...) FROM ... WHERE.conditionno matching row in const table(JSON 属性:message)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 属性:message)No matching rows after partition pruning(JSON property:message)对于
DELETE或UPDATE,优化器在分区修剪后没有找到可删除或更新的内容。这在意义上类似于SELECT语句的Impossible WHERE条件。ForDELETEorUPDATE, the optimizer found nothing to delete or update after partition pruning. It is similar in meaning toImpossible WHEREforSELECTstatements.No tables used(JSON 属性:message)No tables used(JSON property:message)查询没有
FROM子句,或有FROM DUAL子句。The query has noFROMclause, or has aFROM DUALclause.对于
INSERT或REPLACE语句,当没有SELECT部分时,EXPLAIN会显示此值。例如,对于EXPLAIN INSERT INTO t VALUES(10)它会出现,因为这相当于EXPLAIN INSERT INTO t SELECT 10 FROM DUAL。ForINSERTorREPLACEstatements,EXPLAINdisplays this value when there is noSELECTpart. For example, it appears forEXPLAIN INSERT INTO t VALUES(10)because that is equivalent toEXPLAIN INSERT INTO t SELECT 10 FROM DUAL.Not exists(JSON 属性:message)Not exists(JSON property:message)MySQL 能够对查询进行
LEFT JOIN优化,并且在找到符合LEFT JOIN条件的一行后,不会为之前的行组合检查该表中的更多行。以下是可以通过这种方式优化的查询类型示例:MySQL was able to do aLEFT JOINoptimization on the query and does not examine more rows in this table for the previous row combination after it finds one row that matches theLEFT JOINcriteria. 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.id WHERE t2.id IS NULL;
假设
t2.id被定义为NOT NULL。在这种情况下,MySQL 会扫描t1并使用t1.id的值查找t2中的行。如果 MySQL 在t2中找到匹配的行,它就知道t2.id永远不可能为NULL,并且不会扫描t2中具有相同id值的其余行。换句话说,对于t1中的每一行,MySQL 只需要在t2中执行一次查找,而不管t2中实际有多少行匹配。Assume thatt2.idis defined asNOT NULL. In this case, MySQL scanst1and looks up the rows int2using the values oft1.id. If MySQL finds a matching row int2, it knows thatt2.idcan never beNULL, and does not scan through the rest of the rows int2that have the sameidvalue. In other words, for each row int1, MySQL needs to do only a single lookup int2, regardless of how many rows actually match int2.这也可能表示形式为
WHERE或NOT IN (subquery)的NOT EXISTS (subquery)条件已在内部被转换为反连接。这会移除子查询,并将其表引入到最顶层查询的计划中,从而改进成本规划。通过合并半连接和反连接,优化器可以更自由地重新排序执行计划中的表,在某些情况下会产生更快的执行计划。This can also indicate that aWHEREcondition of the formNOT IN (orsubquery)NOT EXISTS (has been transformed internally into an antijoin. This removes the subquery and brings its tables into the plan for the topmost query, providing improved cost planning. By merging semijoins and antijoins, the optimizer can reorder tables in the execution plan more freely, in some cases resulting in a faster plan.subquery)你可以通过在执行
EXPLAIN后检查Message的SHOW WARNINGS列,或者查看EXPLAIN FORMAT=TREE的输出,来确定给定查询是否进行了反连接转换。You can see when an antijoin transformation is performed for a given query by checking theMessagecolumn fromSHOW WARNINGSfollowing execution ofEXPLAIN, or in the output ofEXPLAIN FORMAT=TREE.Note反连接是半连接的补集
。反连接返回所有来自table_aJOINtable_bONconditiontable_a的行,对于这些行,中没有匹配的行table_b变量指示优化器在每个不完整计划的condition.An antijoin is the complement of a semijoin. The antijoin returns all rows fromtable_aJOINtable_bONconditiontable_afor which there is no row intable_bwhich matchescondition.Plan isn't ready yet(JSON 属性:无)Plan isn't ready yet(JSON property: none)当优化器尚未完成为在命名连接中执行的语句创建执行计划时,此值会在
EXPLAIN FOR CONNECTION中出现。如果执行计划输出由多行组成,根据优化器确定完整执行计划的进度,它们中的任何一行或所有行都可能具有此Extra值。This value occurs withEXPLAIN FOR CONNECTIONwhen 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 thisExtravalue, depending on the progress of the optimizer in determining the full execution plan.Range checked for each record (index map: N)(JSON 属性:message)Range checked for each record (index map:(JSON property:N)message)MySQL 没有找到可用的良好索引,但发现某些索引在前面表的列值已知后可能会被使用。对于前面表中的每一行组合,MySQL 会检查是否可以使用
range或index_merge访问方法来检索行。这不是非常快,但比完全没有索引进行连接要快。适用条件如 第 10.2.1.2 节,“范围优化” 和 第 10.2.1.3 节,“索引合并优化” 所述,例外情况是前面表的所有列值都已知并被视为常量。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 arangeorindex_mergeaccess 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 10.2.1.2, “Range Optimization”, and Section 10.2.1.3, “Index Merge Optimization”, with the exception that all column values for the preceding table are known and considered to be constants.索引的编号从 1 开始,顺序与
SHOW INDEX为表显示的顺序相同。索引映射值N是一个位掩码值,用于指示哪些索引是候选索引。例如,值0x19(二进制 11001)表示索引 1、4 和 5 被考虑。Indexes are numbered beginning with 1, in the same order as shown bySHOW INDEXfor the table. The index map valueNis a bitmask value that indicates which indexes are candidates. For example, a value of0x19(binary 11001) means that indexes 1, 4, and 5 are considered.Recursive(JSON 属性:recursive)Recursive(JSON property:recursive)这表示该行适用于递归公共表表达式的递归
SELECT部分。见第 15.2.20 节,“WITH(通用表表达式)”。This indicates that the row applies to the recursiveSELECTpart of a recursive common table expression. See Section 15.2.20, “WITH (Common Table Expressions)”.Rematerialize(JSON 属性:rematerialize)Rematerialize(JSON property:rematerialize)Rematerialize (X,...)显示在表T的EXPLAIN行中,其中X是任何横向派生表,当读取表T的新行时,该派生表的重新生成将被触发。例如:Rematerialize (X,...)is displayed in theEXPLAINrow for tableT, whereXis any lateral derived table whose rematerialization is triggered when a new row ofTis read. For example:SELECT ... FROM t, LATERAL (
derived table that refers to t) AS dt ...每次顶层查询处理新行
t时,派生表的内容都会重新生成以保持最新状态。The content of the derived table is rematerialized to bring it up to date each time a new row oftis processed by the top query.Scanned N databases(JSON 属性:message)Scanned(JSON property:Ndatabasesmessage)这表示服务器在处理对
INFORMATION_SCHEMA表的查询时执行的目录扫描次数,如 第 10.2.3 节,“优化 INFORMATION_SCHEMA 查询” 中所述。N的值可以是 0、1 或all。This indicates how many directory scans the server performs when processing a query forINFORMATION_SCHEMAtables, as described in Section 10.2.3, “Optimizing INFORMATION_SCHEMA Queries”. The value ofNcan be 0, 1, orall.Select tables optimized away(JSON 属性:message)Select tables optimized away(JSON property:message)优化器确定了 1)最多应该返回一行,和 2)为了产生这一行,必须读取一组确定的行。当要读取的行可以在优化阶段读取时(例如,通过读取索引行),在查询执行期间就不需要读取任何表。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.
当查询是隐式分组(包含聚合函数但没有
GROUP BY子句)时,第一个条件就满足。第二个条件是在每个使用的索引上进行一次行查找时满足。读取的索引数量决定了需要读取的行数。The first condition is fulfilled when the query is implicitly grouped (contains an aggregate function but noGROUP BYclause). 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;
假设可以通过读取一个索引行来获取
MIN(c1),并且可以通过读取来自不同索引的一行来获取MIN(c2)。也就是说,对于每个列c1和c2,存在一个索引,其中该列是索引的第一列。在这种情况下,会返回一行,这是通过读取两行确定的行生成的。Suppose thatMIN(c1)can be retrieved by reading one index row andMIN(c2)can be retrieved by reading one row from a different index. That is, for each columnc1andc2, 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.如果要读取的行不是确定的,则不会出现这个
Extra值。考虑以下查询:ThisExtravalue does not occur if the rows to read are not deterministic. Consider this query:SELECT MIN(c2) FROM t1 WHERE c1 <= 10;
假设
(c1, c2)是一个覆盖索引。使用此索引,必须扫描所有c1 <= 10的行以找到最小的c2值。相比之下,考虑以下查询:Suppose that(c1, c2)is a covering index. Using this index, all rows withc1 <= 10must be scanned to find the minimumc2value. By contrast, consider this query:SELECT MIN(c2) FROM t1 WHERE c1 = 10;
在这种情况下,第一个索引行中
c1 = 10的行包含最小的c2值。只需读取一行即可生成返回的行。In this case, the first index row withc1 = 10contains the minimumc2value. Only one row must be read to produce the returned row.对于维护每个表确切行数的存储引擎(例如
MyISAM,但不包括InnoDB),当COUNT(*)查询缺少WHERE条件或条件总是为真,且没有GROUP BY子句时,可能会出现这个Extra值。(这是隐式分组查询的一个实例,其中存储引擎会影响是否可以读取到确定数量的行。)For storage engines that maintain an exact row count per table (such asMyISAM, but notInnoDB), thisExtravalue can occur forCOUNT(*)queries for which theWHEREclause is missing or always true and there is noGROUP BYclause. (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_table、Open_frm_only、Open_full_table(JSON 属性:message)Skip_open_table,Open_frm_only,Open_full_table(JSON property:message)这些值表示适用于
INFORMATION_SCHEMA表查询的文件打开优化。These values indicate file-opening optimizations that apply to queries forINFORMATION_SCHEMAtables.Skip_open_table:表文件无需打开。信息已可从数据字典中获取。Skip_open_table: Table files do not need to be opened. The information is already available from the data dictionary.Open_frm_only:表信息只需读取数据字典。Open_frm_only: Only the data dictionary need be read for table information.Open_full_table:未优化的信息查找。表信息必须通过读取数据字典和表文件来获取。Open_full_table: Unoptimized information lookup. Table information must be read from the data dictionary and by reading table files.
Start temporary,End temporary(JSON 属性:message)Start temporary,End temporary(JSON property:message)这表示半连接重复去除策略中使用了临时表。This indicates temporary table use for the semijoin Duplicate Weedout strategy.
unique row not found(JSON 属性:message)unique row not found(JSON property:message)对于如
SELECT ... FROM tbl_name的查询,没有行满足表上UNIQUE索引或PRIMARY KEY的条件。For a query such asSELECT ... FROM, no rows satisfy the condition for atbl_nameUNIQUEindex orPRIMARY KEYon the table.Using filesort(JSON 属性:using_filesort)Using filesort(JSON property:using_filesort)MySQL 必须进行额外的操作以确定如何按排序顺序检索行。排序是通过根据连接类型遍历所有行并为所有符合
WHERE子句的行存储排序键和行指针来完成的。然后对键进行排序,并按排序顺序检索行。请参阅 第 10.2.1.16 节,“ORDER BY 优化”。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 theWHEREclause. The keys then are sorted and the rows are retrieved in sorted order. See Section 10.2.1.16, “ORDER BY Optimization”.Using index(JSON 属性:using_index)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.
对于具有用户定义聚簇索引的
InnoDB表,即使Extra列中没有Using index,也可以使用该索引。如果type是index且key是PRIMARY,则属于这种情况。ForInnoDBtables that have a user-defined clustered index, that index can be used even whenUsing indexis absent from theExtracolumn. This is the case iftypeisindexandkeyisPRIMARY.使用的任何覆盖索引的信息会在
EXPLAIN FORMAT=TRADITIONAL和EXPLAIN FORMAT=JSON中显示。在EXPLAIN FORMAT=TREE中也会显示。Information about any covering indexes used is shown forEXPLAIN FORMAT=TRADITIONALandEXPLAIN FORMAT=JSON. It is also shown forEXPLAIN FORMAT=TREE.Using index condition(JSON 属性:using_index_condition)Using index condition(JSON property:using_index_condition)表通过访问索引元组并首先测试它们来读取,从而确定是否读取完整的表行。通过这种方式,索引信息用于推迟(“下推”)读取完整表行,除非有必要。请参见 第 10.2.1.6 节,“索引条件下推优化”。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 10.2.1.6, “Index Condition Pushdown Optimization”.
Using index for group-by(JSON 属性:using_index_for_group_by)Using index for group-by(JSON property:using_index_for_group_by)类似于
Using index表访问方法,Using index for group-by表示 MySQL 找到了一个索引,可以用来检索GROUP BY或DISTINCT查询的所有列,而无需对实际表进行任何额外的磁盘访问。此外,该索引以最有效的方式使用,因此对于每个组,只读取少量索引条目。详情请参见 第 10.2.1.17 节,“GROUP BY 优化”。Similar to theUsing indextable access method,Using index for group-byindicates that MySQL found an index that can be used to retrieve all columns of aGROUP BYorDISTINCTquery 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 10.2.1.17, “GROUP BY Optimization”.Using index for skip scan(JSON 属性:using_index_for_skip_scan)Using index for skip scan(JSON property:using_index_for_skip_scan)表示使用 Skip Scan 访问方法。请参见 Skip Scan 范围访问方法。Indicates that the Skip Scan access method is used. See Skip Scan Range Access Method.
Using join buffer (Block Nested Loop),Using join buffer (Batched Key Access),Using join buffer (hash join)(JSON 属性:using_join_buffer)Using join buffer (Block Nested Loop),Using join buffer (Batched Key Access),Using join buffer (hash join)(JSON property:using_join_buffer)来自早期连接的表会分批读入连接缓冲区,然后其行会从缓冲区中使用以与当前表执行连接。
(Block Nested Loop)表示使用块嵌套循环算法,(Batched Key Access)表示使用批量键访问算法,(hash join)表示使用哈希连接。也就是说,来自EXPLAIN输出中前一行表的键会被缓存,并且匹配的行会从出现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,(Batched Key Access)indicates use of the Batched Key Access algorithm, and(hash join)indicates use of a hash join. That is, the keys from the table on the preceding line of theEXPLAINoutput are buffered, and the matching rows are fetched in batches from the table represented by the line in whichUsing join bufferappears.在 JSON 格式的输出中,
using_join_buffer的值总是Block Nested Loop、Batched Key Access或hash join之一。In JSON-formatted output, the value ofusing_join_bufferis always one ofBlock Nested Loop,Batched Key Access, orhash join.有关哈希连接的更多信息,请参见 第 10.2.1.4 节,“哈希连接优化”。For more information about hash joins, see Section 10.2.1.4, “Hash Join Optimization”.
有关批量键访问算法的信息,请参见 批量键访问连接。See Batched Key Access Joins, for information about the Batched Key Access algorithm.
Using MRR(JSON 属性:message)Using MRR(JSON property:message)表使用多范围读取优化策略进行读取。请参见 第 10.2.1.11 节,“多范围读取优化”。Tables are read using the Multi-Range Read optimization strategy. See Section 10.2.1.11, “Multi-Range Read Optimization”.
Using sort_union(...)、Using union(...)、Using intersect(...)(JSON 属性:message)Using sort_union(...),Using union(...),Using intersect(...)(JSON property:message)这些表示用于
index_merge联接类型的索引扫描合并的特定算法。参见 第 10.2.1.3 节,“索引合并优化”。These indicate the particular algorithm showing how index scans are merged for theindex_mergejoin type. See Section 10.2.1.3, “Index Merge Optimization”.Using temporary(JSON 属性:using_temporary_table)Using temporary(JSON property:using_temporary_table)为了解析查询,MySQL 需要创建一个临时表来存储结果。如果查询包含
GROUP BY和ORDER BY并且列的顺序不同,通常会发生这种情况。To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query containsGROUP BYandORDER BYclauses that list columns differently.Using where(JSON 属性:attached_condition)Using where(JSON property:attached_condition)WHERE子句用于限制哪些行与下一个表匹配或发送到客户端。除非您特别打算从表中获取或检查所有行,否则如果Extra的值不是Using where并且表连接类型是ALL或index,可能说明您的查询有问题。AWHEREclause 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 theExtravalue is notUsing whereand the table join type isALLorindex.Using where在 JSON 格式输出中没有直接对应;attached_condition属性包含使用的任何WHERE条件。Using wherehas no direct counterpart in JSON-formatted output; theattached_conditionproperty contains anyWHEREcondition used.Using where with pushed condition(JSON 属性:message)Using where with pushed condition(JSON property:message)此项仅适用于
NDB表 仅。这意味着 NDB Cluster 正在使用条件下推优化来提高对非索引列与常量之间直接比较的效率。在这种情况下,条件会被 “下推” 到集群的数据节点,并在所有数据节点上同时评估。这消除了通过网络发送不匹配行的需要,并且在条件下推可能使用但未使用的情况下,可以将此类查询的速度提高 5 到 10 倍。更多信息,请参见 第 10.2.1.5 节,“引擎条件下推优化”。This item applies toNDBtables only. It means that NDB 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 10.2.1.5, “Engine Condition Pushdown Optimization”.Zero limit(JSON 属性:message)Zero limit(JSON property:message)查询包含
LIMIT 0子句,因此无法选择任何行。The query had aLIMIT 0clause and cannot select any rows.
你可以通过取 EXPLAIN 输出中 rows 列的值的乘积,来大致判断一个连接的好坏。这应该能大概告诉你 MySQL 执行查询时必须检查多少行。如果你使用 max_join_size 系统变量来限制查询,这个行乘积也会用于确定执行哪些多表 SELECT 语句,以及中止哪些语句。参见 第 7.1.1 节,“配置服务器”。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 7.1.1, “Configuring the Server”.
下面的示例展示了如何基于 EXPLAIN 提供的信息逐步优化多表连接。The following example shows how a multiple-table join can be
optimized progressively based on the information provided by
EXPLAIN.
假设你有下面显示的 SELECT 语句,并且计划使用 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.CUSTNAME
FROM tt, et, et AS et_1, do
WHERE tt.SubmitTime IS NULL
AND tt.ActualPC = et.EMPLOYID
AND tt.AssignedPC = et_1.EMPLOYID
AND tt.ClientID = do.CUSTNMBR;
对于这个例子,做出以下假设:For this example, make the following assumptions:
正在比较的列已声明如下。The columns being compared have been declared as follows.
表Table 列Column 数据类型Data Type ttActualPCActualPCCHAR(10)ttAssignedPCAssignedPCCHAR(10)ttClientIDClientIDCHAR(10)etEMPLOYIDEMPLOYIDCHAR(15)doCUSTNMBRCUSTNMBRCHAR(15)这些表具有以下索引。The tables have the following indexes.
表Table 索引Index ttActualPCActualPCttAssignedPCAssignedPCttClientIDClientIDetEMPLOYID(主键)EMPLOYID(primary key)doCUSTNMBR(主键)CUSTNMBR(primary key)tt.ActualPC的值分布不均。Thett.ActualPCvalues are not evenly distributed.
最初,在执行任何优化之前,EXPLAIN 语句产生以下信息: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 3872
ClientID,
ActualPC
Range checked for each record (index map: 0x23)
因为每个表的 type 都是 ALL,所以这个输出表明 MySQL 正在生成所有表的笛卡尔积;也就是说,每一种行的组合都会被生成。这需要相当长的时间,因为必须检查每个表的行数的乘积。就当前的情况而言,这个乘积是 74 × 2135 × 74 × 3872 = 45,268,558,720 行。如果表更大,你可以想象需要多长时间才能完成。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.
这里的一个问题是,如果列被声明为相同的类型和大小,MySQL 可以更高效地使用索引。在这种情况下,如果 VARCHAR 和 CHAR 被声明为相同大小,它们将被视为相同。tt.ActualPC 被声明为 CHAR(10),而 et.EMPLOYID 为 CHAR(15),因此存在长度不匹配的问题。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.
要解决列长度之间的差异,可以使用 ALTER TABLE 将 ActualPC 的长度从 10 个字符延长到 15 个字符: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);
现在 tt.ActualPC 和 et.EMPLOYID 都是 VARCHAR(15)。再次执行 EXPLAIN 语句产生以下结果: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 Using
ClientID, where
ActualPC
do ALL PRIMARY NULL NULL NULL 2135
Range checked for each record (index map: 0x1)
et_1 ALL PRIMARY NULL NULL NULL 74
Range checked for each record (index map: 0x1)
et eq_ref PRIMARY PRIMARY 15 tt.ActualPC 1
这不是完美的,但要好得多:rows 值的乘积减少了 74 倍。这个版本可以在几秒钟内执行完毕。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.
可以进行第二次更改,以消除 tt.AssignedPC =
et_1.EMPLOYID 和 tt.ClientID =
do.CUSTNMBR 比较中的列长度不匹配: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);
在修改之后,EXPLAIN 产生如下所示的输出: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 Using
ClientID, where
ActualPC
et_1 eq_ref PRIMARY PRIMARY 15 tt.AssignedPC 1
do eq_ref PRIMARY PRIMARY 15 tt.ClientID 1
此时,该查询几乎已经优化到最佳状态。剩下的问题是,默认情况下,MySQL 假设 tt.ActualPC 列中的值是均匀分布的,而对于 tt 表来说情况并非如此。幸运的是,可以很容易地告诉 MySQL 分析键的分布: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;
有了额外的索引信息后,连接效果非常好,EXPLAIN 生成如下结果: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 Using
ClientID, where
ActualPC
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
来自 EXPLAIN 输出中的 rows 列是 MySQL 联接优化器的一个有根据的估计值。通过将 rows 乘积与查询实际返回的行数进行比较,检查这些数字是否接近实际情况。如果数字差别很大,你可以尝试在 SELECT 语句中使用 STRAIGHT_JOIN,并尝试在 FROM 子句中以不同顺序列出表,以获得更好的性能。不过,STRAIGHT_JOIN 可能会阻止索引使用,因为它会禁用半连接转换。请参见 使用半连接转换优化 IN 和 EXISTS 子查询谓词。
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 semijoin transformations. See
Optimizing IN and EXISTS Subquery Predicates with Semijoin Transformations.)
在某些情况下,当 EXPLAIN
SELECT 与子查询一起使用时,可以执行修改数据的语句;欲了解更多信息,请参见 第 15.2.15.8 节,“派生表”。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 15.2.15.8, “Derived Tables”.