MySql EXPLAIN Output Format(Mysql执行计划分析参数)
2016-03-30 16:14
746 查看
转载地址:http://dev.mysql.com/doc/refman/5.6/en/explain-extended.html
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.
When the
Section 8.8.3, “EXPLAIN EXTENDED Output Format”.
Note
You cannot use the
Each output row from
Table 8.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
Table 8.1 EXPLAIN Output Columns
Note
JSON properties which are
The
The type of
Section 13.2.10.7, “Correlated Subqueries”.
Cacheability of subqueries differs from caching of query results in the query cache (which is described in
Section 8.10.3.1, “How the Query Cache Operates”). Subquery caching occurs during query execution, whereas the query cache is used to store results only after query execution finishes.
When you specify
The name of the table to which the row of output refers. This can also be one of the following values:
Section 8.2.1.18.2, “Optimizing Subqueries with Subquery Materialization”.
The partitions from which records would be matched by the query. This column is displayed only if the
Section 19.3.5, “Obtaining Information About Partitions”.
The join type. For descriptions of the different types, see
The
If this column is
Section 13.1.7, “ALTER TABLE Syntax”.
To see what indexes a table has, use
The
It is possible that
index scan is more efficient than a data row scan.
For
To force MySQL to use or ignore an index listed in the
Section 8.9.3, “Index Hints”.
For
myisamchk --analyze does the same as
Section 7.6, “MyISAM Table Maintenance and Crash Recovery”.
The
The
If the value is
The
For
The
This column contains additional information about how MySQL resolves the query. For descriptions of the different values, see
There is no single JSON property corresponding to the
The table has only one row (= system table). This is a special case of the
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.
SELECT * FROM
[/code]
One row is read from this table for each combination of rows from the previous tables. Other than the
SELECT * FROM
AND
[/code]
All rows with matching index values are read from this table for each combination of rows from the previous tables.
SELECT * FROM
SELECT * FROM
AND
[/code]
The join is performed using a
This join type is like
[/code]
See
Section 8.2.1.8, “IS NULL Optimization”.
This join type indicates that the Index Merge optimization is used. In this case, the
Section 8.2.1.4, “Index Merge Optimization”.
This type replaces
[/code]
efficiency.
This join type is similar to
[/code]
Only rows that are in a given range are retrieved, using an index to select the rows. The
SELECT * FROM
SELECT * FROM
SELECT * FROM
[/code]
The
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, the
A full table scan is performed using reads from the index to look up data rows in index order.
MySQL can use this join type when the query uses only columns that are part of a single index.
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 marked
the
If you want to make your queries as fast as possible, look out for
This table is referenced as the child of
For a query such as
For
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.
The semi-join FirstMatch join shortcutting strategy is used for
This occurs for subquery optimization as a fallback strategy when the optimizer cannot use an index-lookup access method.
The
The
MySQL has read all
The semi-join LooseScan strategy is used.
Before MySQL 5.6.7, this indicates use of a single materialized temporary table. If
As of MySQL 5.6.7, materialization is indicated by rows with a
No row satisfies the condition for a query such as
For a query with a join, there was an empty table or a table with no rows satisfying a unique index condition.
For
The query has no
For
MySQL was able to do a
Assume that
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
Section 8.2.1.3, “Range Optimization”, and
Section 8.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
This indicates how many directory scans the server performs when processing a query for
Section 8.2.4, “Optimizing INFORMATION_SCHEMA Queries”. The value of
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
Consider the following implicitly grouped query:
Suppose that
This
Suppose that
In this case, the first index row with
For storage engines that maintain an exact row count per table (such as
These values indicate file-opening optimizations that apply to queries for
Section 8.2.4, “Optimizing INFORMATION_SCHEMA Queries”.
Before MySQL 5.6.7, this indicates use of multiple materialized temporary tables. If
As of MySQL 5.6.7, materialization is indicated by rows with a
This indicates temporary table use for the semi-join Duplicate Weedout strategy.
For a query such as
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
Section 8.2.1.15, “ORDER BY Optimization”.
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
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 8.2.1.6, “Index Condition Pushdown Optimization”.
Similar to the
details, see
Section 8.2.1.16, “GROUP BY Optimization”.
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.
In JSON-formatted output, the value of
Tables are read using the Multi-Range Read optimization strategy. See
Section 8.2.1.13, “Multi-Range Read Optimization”.
These indicate how index scans are merged for the
Section 8.2.1.4, “Index Merge Optimization”.
To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query contains
A
This item applies to
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 8.2.1.5, “Engine Condition Pushdown Optimization”.
Section 8.12.2, “Tuning Server Parameters”.
The following example shows how a multiple-table join can be optimized progressively based on the information provided by
Suppose that you have the
For this example, make the following assumptions:
The columns being compared have been declared as follows.
The tables have the following indexes.
The
Initially, before any optimizations have been performed, the
Because
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,
To fix this disparity between column lengths, use
[/code]
Now
This is not perfect, but is much better: The product of the
A second alteration can be made to eliminate the column length mismatches for the
->
[/code]
After that modification,
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
[/code]
With the additional index information, the join is perfect and
The
Section 8.2.1.18.1, “Optimizing Subqueries with Semi-Join Transformations”.)
It is possible in some cases to execute statements that modify data when
Section 13.2.10.8, “Subqueries in the FROM Clause”.
When
a
Here is an example of extended output:
->
*************************** 1. row ***************************id: 1select_type: PRIMARY
table: t1
type: indexpossible_keys: NULL
key: PRIMARY
key_len: 4
ref: NULLrows: 4filtered: 100.00Extra: Using index
*************************** 2. row ***************************id: 2select_type: SUBQUERY
table: t2
type: indexpossible_keys: a
key: a
key_len: 5
ref: NULLrows: 3filtered: 100.00Extra: Using index
2 rows in set, 1 warning (0.00 sec)
mysql>
*************************** 1. row ***************************
Level: Note
Code: 1003
Message: /* select#1 */ select `test`.`t1`.`a` AS `a`,
<in_optimizer>(`test`.`t1`.`a`,`test`.`t1`.`a` in
( <materialize> (/* select#2 */ select `test`.`t2`.`a`
from `test`.`t2` where 1 having 1 ),
<primary_index_lookup>(`test`.`t1`.`a` in
<temporary table> on <auto_key>
where ((`test`.`t1`.`a` = `materialized-subquery`.`a`))))) AS `t1.aIN (SELECT t2.a FROM t2)` from `test`.`t1`
1 row in set (0.00 sec)
[/code]
As of MySQL 5.6.3,
Because the statement displayed by
The following list describes special markers that can appear in
An automatically generated key for a temporary table.
The expression (such as a scalar subquery) is executed once and the resulting value is saved in memory for later use. For results consisting of multiple values, a temporary table may be created and you will see
The subquery predicate is converted to an
This is an internal optimizer object with no user significance.
The query fragment is processed using an index lookup to find qualifying rows.
If the condition is true, evaluate to
A test to verify that the expression does not evaluate to
Subquery materialization is used.
The query fragment is processed using a primary key lookup to find qualifying rows.
This is an internal optimizer object with no user significance.
The
A semi-join operation.
Section 8.2.1.18.1, “Optimizing Subqueries with Semi-Join Transformations”.
This represents an internal temporary table created to cache an intermediate result.
When some tables are of
The
EXPLAINstatement provides information about the execution plan for a
SELECTstatement.
EXPLAINreturns a row of information for each table used in the
SELECTstatement. 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.
When the
EXTENDEDkeyword is used,
EXPLAINproduces extra information that can be viewed by issuing a
SHOW WARNINGSstatement following the
EXPLAINstatement.
EXPLAIN EXTENDEDalso displays the
filteredcolumn. See
Section 8.8.3, “EXPLAIN EXTENDED Output Format”.
Note
You cannot use the
EXTENDEDand
PARTITIONSkeywords together in the same
EXPLAINstatement. In MySQL 5.6.5 and later, neither of these keywords can be used together with the
FORMAToption. (
FORMAT=JSONcauses
EXPLAINto display extended and partition information automatically; using
FORMAT=TRADITIONALhas no effect on
EXPLAINoutput.)
EXPLAINOutput Columns
EXPLAINJoin Types
EXPLAINExtra Information
EXPLAINOutput Interpretation
EXPLAIN Output Columns
This section describes the output columns produced byEXPLAIN. Later sections provide additional information about the
typeand
Extracolumns.
Each output row from
EXPLAINprovides information about one table. Each row contains the values summarized in
Table 8.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=JSONis used.
Table 8.1 EXPLAIN Output Columns
Column | JSON Name | Meaning |
---|---|---|
id | select_id | The SELECTidentifier |
select_type | None | The SELECTtype |
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 |
JSON properties which are
NULLare not displayed in JSON-formatted
EXPLAINoutput.
id(JSON name:
select_id)
The
SELECTidentifier. This is the sequential number of the
SELECTwithin the query. The value can be
NULLif the row refers to the union result of other rows. In this case, the
tablecolumn shows a value like
<union>[/code] to indicate that the row refers to the union of the rows withM,[code]N
idvalues of
Mand
N.
select_type(JSON name: none)
The type of
SELECT, which can be any of those shown in the following table. A JSON-formatted
EXPLAINexposes the
SELECTtype as a property of a
query_block, unless it is
SIMPLEor
PRIMARY. The JSON names (where applicable) are also shown in the table.
select_typeValue | JSON Name | Meaning |
---|---|---|
SIMPLE | None | SimpleSELECT(not using UNIONor subqueries) |
PRIMARY | None | OutermostSELECT |
UNION | None | Second or laterSELECTstatement in a UNION |
DEPENDENT UNION | dependent( true) | Second or laterSELECTstatement in a UNION, dependent on outer query |
UNION RESULT | union_result | Result of aUNION. |
SUBQUERY | None | FirstSELECTin subquery |
DEPENDENT SUBQUERY | dependent( true) | FirstSELECTin subquery, dependent on outer query |
DERIVED | None | Derived tableSELECT(subquery in FROMclause) |
MATERIALIZED | materialized_from_subquery | Materialized subquery |
UNCACHEABLE SUBQUERY | cacheable( false) | A subquery for which the result cannot be cached and must be re-evaluated for each row of the outer query |
UNCACHEABLE UNION | cacheable( false) | The second or later select in aUNIONthat belongs to an uncacheable subquery (see UNCACHEABLE SUBQUERY) |
DEPENDENTtypically signifies the use of a correlated subquery. See
Section 13.2.10.7, “Correlated Subqueries”.
DEPENDENT SUBQUERYevaluation differs from
UNCACHEABLE SUBQUERYevaluation. For
DEPENDENT SUBQUERY, the subquery is re-evaluated only once for each set of different values of the variables from its outer context. For
UNCACHEABLE SUBQUERY, the subquery is re-evaluated for each row of the outer context.
Cacheability of subqueries differs from caching of query results in the query cache (which is described in
Section 8.10.3.1, “How the Query Cache Operates”). Subquery caching occurs during query execution, whereas the query cache is used to store results only after query execution finishes.
When you specify
FORMAT=JSONwith
EXPLAIN, the output has no single property directly equivalent to
select_type; the
query_blockproperty corresponds to a given
SELECT. Properties equivalent to most of the
SELECTsubquery types just shown are available (an example being
materialized_from_subqueryfor
MATERIALIZED), and are displayed when appropriate. There are no JSON equivalents for
SIMPLEor
PRIMARY.
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>[/code]: The row refers to the union of the rows withM,[code]N
idvalues of
Mand
N.
<derived: The row refers to the derived table result for the row with anN>
idvalue of
N. A derived table may result, for example, from a subquery in the
FROMclause.
<subquery: The row refers to the result of a materialized subquery for the row with anN>
idvalue of
N. See
Section 8.2.1.18.2, “Optimizing Subqueries with Subquery Materialization”.
partitions(JSON name:
partitions)
The partitions from which records would be matched by the query. This column is displayed only if the
PARTITIONSkeyword is used. The value is
NULLfor nonpartitioned tables. See
Section 19.3.5, “Obtaining Information About Partitions”.
type(JSON name:
access_type)
The join type. For descriptions of the different types, see
EXPLAINJoin Types.
possible_keys(JSON name:
possible_keys)
The
possible_keyscolumn indicates which indexes MySQL can choose from use 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 from
EXPLAIN. That means that some of the keys in
possible_keysmight not be usable in practice with the generated table order.
If this column is
NULL(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 the
WHEREclause 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 with
EXPLAINagain. See
Section 13.1.7, “ALTER TABLE Syntax”.
To see what indexes a table has, use
SHOW INDEX FROM(JSON name:tbl_name.
[code]key
key)
The
keycolumn indicates the key (index) that MySQL actually decided to use. If MySQL decides to use one of the
possible_keysindexes to look up rows, that index is listed as the key value.
It is possible that
keywill name an index that is not present in the
possible_keysvalue. This can happen if none of the
possible_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.
For
InnoDB, a secondary index might cover the selected columns even if the query also selects the primary key because
InnoDBstores the primary key value with each secondary index. If
keyis
NULL, MySQL found no index to use for executing the query more efficiently.
To force MySQL to use or ignore an index listed in the
possible_keyscolumn, use
FORCE INDEX,
USE INDEX, or
IGNORE INDEXin your query. See
Section 8.9.3, “Index Hints”.
For
MyISAMand
NDBtables, running
ANALYZE TABLEhelps the optimizer choose better indexes. For
NDBtables, this also improves performance of distributed pushed-down joins. For
MyISAMtables,
myisamchk --analyze does the same as
ANALYZE TABLE. See
Section 7.6, “MyISAM Table Maintenance and Crash Recovery”.
key_len(JSON name:
key_length)
The
key_lencolumn indicates the length of the key that MySQL decided to use. The length is
NULLif the
keycolumn says
NULL. Note that the value of
key_lenenables you to determine how many parts of a multiple-part key MySQL actually uses.
ref(JSON name:
ref)
The
refcolumn shows which columns or constants are compared to the index named in the
keycolumn to select rows from the table.
If the value is
func, the value used is the result of some function. To see which function, use
EXPLAIN EXTENDEDfollowed by
SHOW WARNINGS. The function might actually be an operator such as an arithmetic operator.
rows(JSON name:
rows)
The
rowscolumn indicates the number of rows MySQL believes it must examine to execute the query.
For
InnoDBtables, this number is an estimate, and may not always be exact.
filtered(JSON name:
filtered)
The
filteredcolumn indicates an estimated percentage of table rows that will be filtered by the table condition. That is,
rowsshows the estimated number of rows examined and
rows×
filtered/
100shows the number of rows that will be joined with previous tables. This column is displayed if you use
EXPLAIN EXTENDED.
Extra(JSON name: none)
This column contains additional information about how MySQL resolves the query. For descriptions of the different values, see
EXPLAINExtra Information.
There is no single JSON property corresponding to the
Extracolumn; however, values that can occur in this column are exposed as JSON properties, or as the text of the
messageproperty.
EXPLAIN Join Types
Thetypecolumn of
EXPLAINoutput describes how tables are joined. In JSON-formatted output, these are found as values of the
access_typeproperty. The following list describes the join types, ordered from the best type to the worst:
system
The table has only one row (= system table). This is a special case of the
constjoin 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.
constis used when you compare all parts of a
PRIMARY KEYor
UNIQUEindex to constant values. In the following queries,
tbl_namecan be used as a
consttable:
SELECT * FROM [code]tbl_nameWHERE
primary_key=1;
SELECT * FROM
tbl_nameWHERE
primary_key_part1=1 AND
primary_key_part2=2;
[/code]
eq_ref
One row is read from this table for each combination of rows from the previous tables. Other than the
systemand
consttypes, 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 a
PRIMARY KEYor
UNIQUE NOT NULLindex.
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 an
eq_refjoin to process
ref_table:
SELECT * FROM [code]ref_table,
other_tableWHERE
ref_table.
key_column=
other_table.
column;
SELECT * FROM
ref_table,
other_tableWHERE
ref_table.
key_column_part1=
other_table.
column
AND
ref_table.
key_column_part2=1;
[/code]
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 a
PRIMARY KEYor
UNIQUEindex (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.
refcan be used for indexed columns that are compared using the
=or
<=>operator. In the following examples, MySQL can use a
refjoin to process
ref_table:
SELECT * FROM [code]ref_tableWHERE
key_column=
expr;
SELECT * FROM
ref_table,
other_tableWHERE
ref_table.
key_column=
other_table.
column;
SELECT * FROM
ref_table,
other_tableWHERE
ref_table.
key_column_part1=
other_table.
column
AND
ref_table.
key_column_part2=1;
[/code]
fulltext
The join is performed using a
FULLTEXTindex.
ref_or_null
This join type is like
ref, but with the addition that MySQL does an extra search for rows that contain
NULLvalues. This join type optimization is used most often in resolving subqueries. In the following examples, MySQL can use a
ref_or_nulljoin to process
ref_table:
SELECT * FROM [code]ref_tableWHERE
key_column=
exprOR
key_columnIS NULL;
[/code]
See
Section 8.2.1.8, “IS NULL Optimization”.
index_merge
This join type indicates that the Index Merge optimization is used. In this case, the
keycolumn in the output row contains a list of indexes used, and
key_lencontains a list of the longest key parts for the indexes used. For more information, see
Section 8.2.1.4, “Index Merge Optimization”.
unique_subquery
This type replaces
eq_reffor some
INsubqueries of the following form:
valueIN (SELECT
primary_keyFROM
single_tableWHERE
some_expr)
[/code]
unique_subqueryis just an index lookup function that replaces the subquery completely for better
efficiency.
index_subquery
This join type is similar to
unique_subquery. It replaces
INsubqueries, but it works for nonunique indexes in subqueries of the following form:
valueIN (SELECT
key_columnFROM
single_tableWHERE
some_expr)
[/code]
range
Only rows that are in a given range are retrieved, using an index to select the rows. The
keycolumn in the output row indicates which index is used. The
key_lencontains the longest key part that was used. The
refcolumn is
NULLfor this type.
rangecan be used when a key column is compared to a constant using any of the
=,
<>,
>,
>=,
<,
<=,
IS NULL,
<=>,
BETWEEN, or
IN()operators:
SELECT * FROM [code]tbl_nameWHERE
key_column= 10;
SELECT * FROM
tbl_nameWHERE
key_columnBETWEEN 10 and 20;
SELECT * FROM
tbl_nameWHERE
key_columnIN (10,20,30);
SELECT * FROM
tbl_nameWHERE
key_part1= 10 AND
key_part2IN (10,20,30);
[/code]
index
The
indexjoin type is the same as
ALL, except that the index tree is scanned. This occurs two ways:
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, the
Extracolumn says
Using index. An index-only scan usually is faster than
ALLbecause the size of the index usually is smaller than the table data.
A full table scan is performed using reads from the index to look up data rows in index order.
Uses indexdoes not appear in the
Extracolumn.
MySQL can use this join type when the query uses only columns that are part of a single index.
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 marked
const, and usually very bad in all other cases. Normally, you can avoid
ALLby adding indexes that enable row retrieval from the table based on constant values or column values from earlier tables.
EXPLAIN Extra Information
TheExtracolumn of
EXPLAINoutput 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
Extravalue. For some of these, there is a specific property. The others display as the text of the
messageproperty.
If you want to make your queries as fast as possible, look out for
Extracolumn values of
Using filesortand
Using temporary, or, in JSON-formatted
EXPLAINoutput, for
using_filesortand
using_temporary_tableproperties equal to
true.
Child of '(JSON:table' pushed join@1
messagetext)
This table is referenced as the child of
tablein 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_pushdownserver system variable for more information and examples.
const row not found(JSON property:
const_row_not_found)
For a query such as
SELECT ... FROM(JSON property:tbl_name, the table was empty.
[code]Deleting all rows
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
Extravalue 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((JSON property:tbl_name)
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
HAVINGclause is always false and cannot select any rows.
Impossible WHERE(JSON property:
message)
The
WHEREclause 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
WHEREclause is always false.
LooseScan()[/code] (JSON property:m..[code]n
message)
The semi-join LooseScan strategy is used.
mand
nare key part numbers.
Materialize,
Scan(JSON:
messagetext)
Before MySQL 5.6.7, this indicates use of a single materialized temporary table. If
Scanis present, no temporary table index is used for table reads. Otherwise, an index lookup is used. See also the
Start materializeentry.
As of MySQL 5.6.7, materialization is indicated by rows with a
select_typevalue of
MATERIALIZEDand rows with a
tablevalue of
<subquery.N>
No matching min/max row(JSON property:
message)
No row satisfies the condition for a query such as
SELECT MIN(...) FROM ... WHERE(JSON property:condition.
[code]no matching row in const table
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
DELETEor
UPDATE, the optimizer found nothing to delete or update after partition pruning. It is similar in meaning to
Impossible WHEREfor
SELECTstatements.
No tables used(JSON property:
message)
The query has no
FROMclause, or has a
FROM DUALclause.
For
INSERTor
REPLACEstatements,
EXPLAINdisplays this value when there is no
SELECTpart. 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 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 the
LEFT 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.idWHERE t2.id IS NULL;
Assume that
t2.idis defined as
NOT NULL. In this case, MySQL scans
t1and looks up the rows in
t2using the values of
t1.id. If MySQL finds a matching row in
t2, it knows that
t2.idcan never be
NULL, and does not scan through the rest of the rows in
t2that have the same
idvalue. 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.
Range checked for each record (index map:(JSON property:N)
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_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 8.2.1.3, “Range Optimization”, and
Section 8.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 INDEXfor the table. The index map value
Nis 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(JSON property:Ndatabases
message)
This indicates how many directory scans the server performs when processing a query for
INFORMATION_SCHEMAtables, as described in
Section 8.2.4, “Optimizing INFORMATION_SCHEMA Queries”. The value of
Ncan 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 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;
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
c1and
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
Extravalue 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 <= 10must be scanned to find the minimum
c2value. By contrast, consider this query:
SELECT MIN(c2) FROM t1 WHERE c1 = 10;
In this case, the first index row with
c1 = 10contains the minimum
c2value. 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
Extravalue can occur for
COUNT(*)queries for which the
WHEREclause is missing or always true and there is no
GROUP 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_trigger_only,
Open_full_table(JSON property:
message)
These values indicate file-opening optimizations that apply to queries for
INFORMATION_SCHEMAtables, as described in
Section 8.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
.frmfile need be opened.
Open_trigger_only: Only the table's
.TRGfile need be opened.
Open_full_table: The unoptimized information lookup. The
.frm,
.MYD, and
.MYIfiles must be opened.
Start materialize,
End materialize,
Scan(JSON:
messagetext)
Before MySQL 5.6.7, this indicates use of multiple materialized temporary tables. If
Scanis present, no temporary table index is used for table reads. Otherwise, an index lookup is used. See also the
Materializeentry.
As of MySQL 5.6.7, materialization is indicated by rows with a
select_typevalue of
MATERIALIZEDand rows with a
tablevalue of
<subquery.N>
Start temporary,
End 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 ... FROMindex ortbl_name, no rows satisfy the condition for a [code]
UNIQUE
PRIMARY KEYon 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
WHEREclause. The keys then are sorted and the rows are retrieved in sorted order. See
Section 8.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
InnoDBtables that have a user-defined clustered index, that index can be used even when
Using indexis absent from the
Extracolumn. This is the case if
typeis
indexand
keyis
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 8.2.1.6, “Index Condition Pushdown Optimization”.
Using index for group-by(JSON property:
using_index_for_group_by)
Similar to the
Using indextable access method,
Using index for group-byindicates that MySQL found an index that can be used to retrieve all columns of a
GROUP BYor
DISTINCTquery 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 8.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
EXPLAINoutput will be buffered, and the matching rows will be fetched in batches from the table represented by the line in which
Using join bufferappears.
In JSON-formatted output, the value of
using_join_bufferis always either one of
Block Nested Loopor
Batched Key Access.
Using MRR(JSON property:
message)
Tables are read using the Multi-Range Read optimization strategy. See
Section 8.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_mergejoin type. See
Section 8.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 BYand
ORDER BYclauses that list columns differently.
Using where(JSON property:
attached_condition)
A
WHEREclause 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
Extravalue is not
Using whereand the table join type is
ALLor
index.
Using wherehas no direct counterpart in JSON-formatted output; the
attached_conditionproperty contains any
WHEREcondition used.
Using where with pushed condition(JSON property:
message)
This item applies to
NDBtables 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 8.2.1.5, “Engine Condition Pushdown Optimization”.
EXPLAIN Output Interpretation
You can get a good indication of how good a join is by taking the product of the values in therowscolumn of the
EXPLAINoutput. This should tell you roughly how many rows MySQL must examine to execute the query. If you restrict queries with the
max_join_sizesystem variable, this row product also is used to determine which multiple-table
SELECTstatements to execute and which to abort. See
Section 8.12.2, “Tuning Server Parameters”.
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
SELECTstatement 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, doWHERE 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 |
---|---|---|
tt | ActualPC | CHAR(10) |
tt | AssignedPC | CHAR(10) |
tt | ClientID | CHAR(10) |
et | EMPLOYID | CHAR(15) |
do | CUSTNMBR | CHAR(15) |
Table | Index |
---|---|
tt | ActualPC |
tt | AssignedPC |
tt | ClientID |
et | EMPLOYID(primary key) |
do | CUSTNMBR(primary key) |
tt.ActualPCvalues are not evenly distributed.
Initially, before any optimizations have been performed, the
EXPLAINstatement 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)
Because
typeis
ALLfor 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,
VARCHARand
CHARare considered the same if they are declared as the same size.
tt.ActualPCis declared as
CHAR(10)and
et.EMPLOYIDis
CHAR(15), so there is a length mismatch.
To fix this disparity between column lengths, use
ALTER TABLEto lengthen
ActualPCfrom 10 characters to 15 characters:
mysql> [code]ALTER TABLE tt MODIFY ActualPC VARCHAR(15);
[/code]
Now
tt.ActualPCand
et.EMPLOYIDare both
VARCHAR(15). Executing the
EXPLAINstatement 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
This is not perfect, but is much better: The product of the
rowsvalues 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.EMPLOYIDand
tt.ClientID = do.CUSTNMBRcomparisons:
mysql> [code]ALTER TABLE tt MODIFY AssignedPC VARCHAR(15),
->
MODIFY ClientID VARCHAR(15);
[/code]
After that modification,
EXPLAINproduces 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
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.ActualPCcolumn are evenly distributed, and that is not the case for the
tttable. Fortunately, it is easy to tell MySQL to analyze the key distribution:
mysql> [code]ANALYZE TABLE tt;
[/code]
With the additional index information, the join is perfect and
EXPLAINproduces 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
The
rowscolumn in the output from
EXPLAINis an educated guess from the MySQL join optimizer. Check whether the numbers are even close to the truth by comparing the
rowsproduct with the actual number of rows that the query returns. If the numbers are quite different, you might get better performance by using
STRAIGHT_JOINin your
SELECTstatement and trying to list the tables in a different order in the
FROMclause. (However,
STRAIGHT_JOINmay prevent indexes from being used because it disables semi-join transformations. See
Section 8.2.1.18.1, “Optimizing Subqueries with Semi-Join Transformations”.)
It is possible in some cases to execute statements that modify data when
EXPLAIN SELECTis used with a subquery; for more information, see
Section 13.2.10.8, “Subqueries in the FROM Clause”.
When
EXPLAINis used with the
EXTENDEDkeyword, the output includes a
filteredcolumn not otherwise displayed. This column indicates the estimated percentage of table rows that will be filtered by the table condition. In addition, the statement produces extra information that can be viewed by issuing
a
SHOW WARNINGSstatement following the
EXPLAINstatement. The
Messagevalue in
SHOW WARNINGSoutput displays how the optimizer qualifies table and column names in the
SELECTstatement, what the
SELECTlooks like after the application of rewriting and optimization rules, and possibly other notes about the optimization process.
Here is an example of extended output:
mysql> [code]EXPLAIN EXTENDED
->
SELECT t1.a, t1.a IN (SELECT t2.a FROM t2) FROM t1\G
*************************** 1. row ***************************id: 1select_type: PRIMARY
table: t1
type: indexpossible_keys: NULL
key: PRIMARY
key_len: 4
ref: NULLrows: 4filtered: 100.00Extra: Using index
*************************** 2. row ***************************id: 2select_type: SUBQUERY
table: t2
type: indexpossible_keys: a
key: a
key_len: 5
ref: NULLrows: 3filtered: 100.00Extra: Using index
2 rows in set, 1 warning (0.00 sec)
mysql>
SHOW WARNINGS\G
*************************** 1. row ***************************
Level: Note
Code: 1003
Message: /* select#1 */ select `test`.`t1`.`a` AS `a`,
<in_optimizer>(`test`.`t1`.`a`,`test`.`t1`.`a` in
( <materialize> (/* select#2 */ select `test`.`t2`.`a`
from `test`.`t2` where 1 having 1 ),
<primary_index_lookup>(`test`.`t1`.`a` in
<temporary table> on <auto_key>
where ((`test`.`t1`.`a` = `materialized-subquery`.`a`))))) AS `t1.aIN (SELECT t2.a FROM t2)` from `test`.`t1`
1 row in set (0.00 sec)
[/code]
As of MySQL 5.6.3,
EXPLAIN EXTENDEDcan be used with
SELECT,
DELETE,
INSERT,
REPLACE, and
UPDATEstatements. However, the following
SHOW WARNINGSstatement displays a nonempty result only for
SELECTstatements. Before MySQL 5.6.3,
EXPLAIN EXTENDEDcan be used only with
SELECTstatements.
Because the statement displayed by
SHOW WARNINGSmay contain special markers to provide information about query rewriting or optimizer actions, the statement is not necessarily valid SQL and is not intended to be executed. The output may also include rows with
Messagevalues that provide additional non-SQL explanatory notes about actions taken by the optimizer.
The following list describes special markers that can appear in
EXTENDEDoutput displayed by
SHOW WARNINGS:
<auto_key>
An automatically generated key for a temporary table.
<cache>(expr)
The expression (such as a scalar subquery) is executed once and the resulting value is saved in memory for later use. For results consisting of multiple values, a temporary table may be created and you will see
<temporary table>instead.
<exists>(query fragment)
The subquery predicate is converted to an
EXISTSpredicate and the subquery is transformed so that it can be used together with the
EXISTSpredicate.
<in_optimizer>(query fragment)
This is an internal optimizer object with no user significance.
<index_lookup>(query fragment)
The query fragment is processed using an index lookup to find qualifying rows.
<if>(,condition,
[code]expr1
expr2)[/code]
If the condition is true, evaluate to
expr1, otherwise
expr2.
<is_not_null_test>(expr)
A test to verify that the expression does not evaluate to
NULL.
<materialize>(query fragment)
Subquery materialization is used.
`materialized-subquery`.in an internal temporary table materialized to hold the result from evaluating a subquery.col_name,
[code]`materialized subselect`.col_name
A reference to the column [code]col_name
<primary_index_lookup>(query fragment)
The query fragment is processed using a primary key lookup to find qualifying rows.
<ref_null_helper>(expr)
This is an internal optimizer object with no user significance.
/* select#N*/
[code]select_stmt
The
SELECTis associated with the row in non-
EXTENDED
EXPLAINoutput that has an
idvalue of
N.
outer_tablessemi join (
inner_tables)[/code]
A semi-join operation.
inner_tablesshows the tables that were not pulled out. See
Section 8.2.1.18.1, “Optimizing Subqueries with Semi-Join Transformations”.
<temporary table>
This represents an internal temporary table created to cache an intermediate result.
When some tables are of
constor
systemtype, expressions involving columns from these tables are evaluated early by the optimizer and are not part of the displayed statement. However, with
FORMAT=JSON, some
consttable accesses are displayed as a
refaccess that uses a const value.
相关文章推荐
- 两种Domain Entity生成方式
- Hdu 2473(并查集删除操作) Junk-Mail Filter
- poj 3378 Crazy Thairs dp+线段树+大数
- QWaitCondition类官方手册
- Failed to start service jboss.network.management
- Debug Assertion Failed Expression: _pFirstBlock==pHead
- HDOJ 1787 GCD Again(欧拉函数)
- HDOJ 1151 Air Raid
- Disneyland of Shanghai
- emulator: warning: opening audio input failed
- 宏杉科技针对传统RAID缺陷推CRAID 3.0
- 【贪心】【codeforces】651B Beautiful Paintings
- ld: 1 duplicate symbol for architecture arm64 clang: error: linker command failed with exit code 1 (
- SDL问题记录:无法识别的链接符号_SDL_main
- (Rails) : NoMethodError: undefined method cost' for BCrypt::Engine:Class
- OpenAIS学习笔记
- 自定义控件三部曲之绘图篇(七)——Paint之函数大汇总
- 我与小娜(44):AlphaGo与微软聊天机器人Tay都是新一代人工智能
- 全局类
- myBaits association的使用