Use explain to query the execution plan of SQL in MySQL

1. What is the MySQL execution plan

       To have a good understanding of the execution plan, you need to have a simple understanding of the basic structure of MySQL and the basic principles of query.

        The functional architecture of MySQL itself is divided into three parts, namely the application layer, the logical layer, and the physical layer. Not only MySQL, but most other database products are divided according to this architecture.

  • The application layer is mainly responsible for interacting with the client, establishing links, remembering the link status, returning data, and responding to requests. This layer deals with the client.
  • The logic layer is mainly responsible for query processing, transaction management and other database function processing. Take query as an example.

        After first receiving the query SQL, the database will immediately allocate a thread to process it. In the first step, the query processor will optimize the SQL query. After optimization, an execution plan will be generated , and then handed over to the plan executor for execution.

        The plan executor needs to access the lower-level transaction manager and the storage manager to operate the data. Their respective divisions of labor are different. Finally, the query structure information is obtained by calling the file of the physical layer, and the final result is responded to the application layer.

  • The physical layer, the files stored on the actual physical disk, mainly include sub-text data files and log files.

   Through the above description, generating an execution plan is an indispensable step for executing a SQL. The performance of a SQL can be seen intuitively by viewing the execution plan. The execution plan provides various query types and levels. View and as a basis for performance analysis.

 

2. How to analyze the execution plan

     MySQL provides us with the explain keyword to visually view the execution plan of a SQL.

     The explain shows how MySQL uses indexes to process select statements and join tables, which can help choose better indexes and write more optimized queries.

      Next we use explain to make a query, as follows:

mysql> explain select * from payment;
+----+-------------+---------+------------+------+---------------+------+---------+------+-------+----------+-------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows  | filtered | Extra |
+----+-------------+---------+------------+------+---------------+------+---------+------+-------+----------+-------+
|  1 | SIMPLE      | payment | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 16086 |   100.00 | NULL  |
+----+-------------+---------+------------+------+---------------+------+---------+------+-------+----------+-------+
1 row in set, 1 warning (0.01 sec)

     There are 12 columns in the query structure. Understanding the meaning of each column is crucial to understanding the execution plan. The following is explained in the form of a table.

column name illustrate
id SELECT identifier, which is the query sequence number of the SELECT.
select_type

SELECT type, which can be any of the following:

  • SIMPLE : Simple SELECT (without using UNION or subqueries)
  • PRIMARY : the outermost SELECT
  • UNION : The second or subsequent SELECT statement in UNION
  • DEPENDENT UNION : The second or subsequent SELECT statement in the UNION, depending on the outer query
  • UNION RESULT : result of UNION
  • SUBQUERY : The first SELECT in a subquery
  • DEPENDENT SUBQUERY : The first SELECT in a subquery, depending on the outer query
  • DERIVED : SELECT of the derived table (subquery of the FROM clause)
table the table referenced by the output row
partitions If the query is based on a partitioned table, displays the partition the query will access.
type

Join type. The various join types are given below, ordered from best to worst:

  • system : The table has only one row (=system table). This is a special case of the const join type.
  • const : The table has at most one matching row, which will be read at the start of the query. Since there is only one row, the column values ​​in this row can be considered constant by the rest of the optimizer. const tables are fast because they are only read once!
  • eq_ref : For each combination of rows from the preceding table, read a row from this table. This is probably the best join type, except for const types.
  • ref : For each combination of rows from the preceding table, all rows with matching index values ​​will be read from this table.
  • ref_or_null : This join type is like ref, but with the addition that MySQL can specifically search for rows containing NULL values.
  • index_merge : This join type indicates that the index merge optimization method is used.
  • unique_subquery : This type replaces the ref of the IN subquery of the following form: value IN (SELECT primary_key FROM single_table WHERE some_expr) unique_subquery is an indexed lookup function that can completely replace subqueries with higher efficiency.
  • index_subquery : This join type is similar to unique_subquery. IN subqueries can be replaced, but only for non-unique indexes in subqueries of the form: value IN (SELECT key_column FROM single_table WHERE some_expr)
  • range : Retrieve only a given range of rows, using an index to select rows.
  • index : This join type is the same as ALL, except that only the index tree is scanned. This is usually faster than ALL because index files are usually smaller than data files.
  • ALL : For each combination of rows from the previous table, a full table scan is performed, indicating that the query needs to be optimized .

Generally speaking, it is necessary to ensure that the query reaches at least the range level, preferably ref.

possible_keys Indicates which index MySQL can use to find rows in this table
key Shows the keys (indexes) that MySQL actually decided to use. If no index is selected, the key is NULL.
key_len Displays the key length that MySQL decided to use. If the key is NULL, the length is NULL. Shorter lengths are better without loss of accuracy
ref Shows which column or constant is used with key to select rows from the table.
rows 显示MySQL认为它执行查询时必须检查的行数。多行之间的数据相乘可以估算要处理的行数。
filtered 显示了通过条件过滤出的行数的百分比估计值。
Extra

该列包含MySQL解决查询的详细信息

  • Distinct:MySQL发现第1个匹配行后,停止为当前的行组合搜索更多的行。
  • Select tables optimized away MySQL根本没有遍历表或索引就返回数据了,表示已经优化到不能再优化了
  • Not exists:MySQL能够对查询进行LEFT JOIN优化,发现1个匹配LEFT JOIN标准的行后,不再为前面的的行组合在该表内检查更多的行。
  • range checked for each record (index map: #):MySQL没有发现好的可以使用的索引,但发现如果来自前面的表的列值已知,可能部分索引可以使用。
  • Using filesort:MySQL需要额外的一次传递,以找出如何按排序顺序检索行,说明查询就需要优化了
  • Using index:从只使用索引树中的信息而不需要进一步搜索读取实际的行来检索表中的列信息。
  • Using temporary:为了解决查询,MySQL需要创建一个临时表来容纳结果,说明查询就需要优化了
  • Using where:WHERE 子句用于限制哪一个行匹配下一个表或发送到客户。
  • Using sort_union(...), Using union(...), Using intersect(...):这些函数说明如何为index_merge联接类型合并索引扫描。
  • Using index for group-by:类似于访问表的Using index方式,Using index for group-by表示MySQL发现了一个索引,可以用来查 询GROUP BY或DISTINCT查询的所有列,而不要额外搜索硬盘访问实际的表。

    根据上述表格,可以在执行计划分析上提供很好的帮助。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325328494&siteId=291194637