当前位置:网站首页>Explain usage, field explanations, and optimization instances of MySQL
Explain usage, field explanations, and optimization instances of MySQL
2022-06-13 03:34:00 【TRX1024】
One 、 Concept
Use EXPLAIN Keyword can simulate optimizer execution SQL Query statement , So they know MySQL How to deal with you SQL Of the statement . Analyze the performance bottleneck of your query statement or table structure .
Two 、 effect
Use EXPLAIN You can understand what you wrote SQL What information is available during execution ?
- Read order of tables
- Operation type of data read operation
- Which indexes can be used
- Which indexes are actually used
- References between tables
- How many rows per table are queried by the optimizer
3、 ... and 、 How to use it?
command :explain + sql
Information contained in the implementation plan :
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+Four 、 Explanation of each field
For the convenience of demonstration , Let's prepare some data first
CREATE TABLE t1(id INT(10) AUTO_INCREMENT,content VARCHAR(100) NULL , PRIMARY KEY (id));
CREATE TABLE t2(id INT(10) AUTO_INCREMENT,content VARCHAR(100) NULL , PRIMARY KEY (id));
CREATE TABLE t3(id INT(10) AUTO_INCREMENT,content VARCHAR(100) NULL , PRIMARY KEY (id));
CREATE TABLE t4(id INT(10) AUTO_INCREMENT,content VARCHAR(100) NULL , PRIMARY KEY (id));
INSERT INTO t1(content) VALUES(CONCAT('t1_',FLOOR(1+RAND()*1000)));
INSERT INTO t2(content) VALUES(CONCAT('t2_',FLOOR(1+RAND()*1000)));
INSERT INTO t3(content) VALUES(CONCAT('t3_',FLOOR(1+RAND()*1000)));
INSERT INTO t4(content) VALUES(CONCAT('t4_',FLOOR(1+RAND()*1000)));According to the information contained in the execution plan given above , Let's explain one by one , The content will be long , Each example is recorded in person , I hope it will help you all .
1.id
First field id, It is select The serial number of the query , Represents execution in a query select Clause ( Subquery ) Or the order of the operation table . To put it bluntly , When sql Statement has subqueries , Or query multiple tables at once , Or there are nested queries , Then we can go through id Fields to see what order they are executed , There are several situations :
(1) id identical , The order of execution is from top to bottom
mysql> explain select * from t1,t2,t3 where t1.id = t2.id and t2.id = t3.id;
+----+-------------+-------+------------+--------+---------------+---------+---------+--------------+------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------------+--------+---------------+---------+---------+--------------+------+-------+
| 1 | SIMPLE | t1 | NULL | ALL | PRIMARY | NULL | NULL | NULL | 1 | NULL |
| 1 | SIMPLE | t2 | NULL | eq_ref | PRIMARY | PRIMARY | 4 | xiaomi.t1.id | 1 | NULL |
| 1 | SIMPLE | t3 | NULL | eq_ref | PRIMARY | PRIMARY | 4 | xiaomi.t1.id | 1 | NULL |
+----+-------------+-------+------------+--------+---------------+---------+---------+--------------+------+-------+
3 rows in set, 1 warning (0.05 sec)From this we can see that , The execution order of these three tables is t1、t2、t3.
(2) id Different , If it's a subquery ,id The sequence number will be incremented ,id The higher the value, the higher the priority , The first to be executed
mysql> explain
-> select t1.id from t1
-> where t1.id in (
-> select t2.id from t2
-> where t2.id in (
-> select t3.id from t3 where t3.content = ''
-> )
-> );
+----+------------------------+-------+------------+--------+---------------+---------+---------+--------------+------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | Extra |
+----+------------------------+-------+------------+--------+---------------+---------+---------+--------------+------+-------+
| 1 | PRIMARY | t1 | NULL | ALL | PRIMARY | NULL | NULL | NULL | 1 | NULL |
| 2 | DEPENENT SUBQUERY | t2 | NULL | eq_ref | PRIMARY | PRIMARY | 4 | xiaomi.t1.id | 1 | NULL |
| 3 | DEPENENT SUBQUERY | t3 | NULL | eq_ref | PRIMARY | PRIMARY | 4 | xiaomi.t1.id | 1 | NULL |
+----+------------------------+-------+------------+--------+---------------+---------+---------+--------------+------+-------+
3 rows in set, 1 warning (0.05 sec)
(3) id It's the same , There are different
mysql> explain select t2.* from t2,(select * from t3 where t3.content='') s3 where s3.id = t2.id;
+----+--------------+---------------+------------+--------+---------------+---------+---------+--------------+------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------+---------------+------------+--------+---------------+---------+---------+--------------+------+-------+
| 1 | PRIMARY | <derived2> | NULL | ALL | PRIMARY | NULL | NULL | NULL | 1 | NULL |
| 1 | PRIMARY | t2 | NULL | eq_ref | PRIMARY | PRIMARY | 4 | xiaomi.t1.id | 1 | NULL |
| 2 | DERIVED | t3 | NULL | eq_ref | PRIMARY | PRIMARY | 4 | xiaomi.t1.id | 1 | NULL |
+----+------------------------------+-------+------------+--------+---------------+---------+---------+--------------+------+-------+
3 rows in set, 1 warning (0.05 sec)id If the same , It can be thought of as a group , From top to bottom ; In all groups ,id The bigger the value is. , The higher the priority , The more you execute the derivation first = DERIVED
2.select_type
select_type Represents the type of query , It is mainly used to distinguish ordinary queries 、 The joint query 、 Complex queries such as subqueries .
| select_type attribute | meaning |
| SIMPLE | ordinary select Inquire about , The query does not contain subqueries or UNION |
| PRIMARY | If the query contains any complex sub parts , The outermost query is marked Primary |
| DERIVED | stay FROM The subqueries contained in the list are marked with DERIVED( derivative ) MySQL These subqueries will be executed recursively , Put the results on the provisional list . |
| SUBQUERY | stay SELECT or WHERE The list contains subqueries |
| DEPEDENT SUBQUERY | stay SELECT or WHERE The list contains subqueries , The subquery is based on the outer layer |
| UNCACHEABLE SUBQUERY | Cannot use cached subqueries |
| UNION | If the second SELECT Appear in the UNION after , Is marked as UNION; if UNION Included in FROM Clause , Outer layer SELECT Will be marked as :DERIVED |
| UNION RESULT | from UNION Table to get the result SELECT |
3.table
Which table is this data based on .
4.type
type Is the access type of the query . Is a more important indicator , The result value from the best to the worst is :
system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index >ALL
We focus on :
system > const > eq_ref > ref > range > index >ALL
Generally speaking , Make sure that the query is at least range Level , It's better to achieve ref.
(1)system
There is only one line in the table ( It's equal to the system table ), This is a const Type of specials , Not usually , This can also be ignored
(2)const
Indicates that it is found through index once ,const For comparison primary key perhaps unique Indexes . Because only one line of data is matched , So soon For example, place the primary key in where In the list ,MySQL You can convert the query to a constant .

(3)eq_ref
Unique index scan , For each index key , Only one record in the table matches it . Common in primary key or unique index scan .

(4)ref
Non unique index scan , Returns all rows that match a single value . In essence, it is also an index access , It returns all rows that match a single value , However , It may find more than one eligible row , So it should be a mixture of search and scan .
Before using the index :

After indexing :

(5)range
Retrieve only rows in the given range , Use an index to select rows .key The column shows which index is used, usually in your where Statement 了 between、<、>、in The range scan index scan is better than the full table scan , Because it just needs to start at a certain point in the index , and The other point of conclusion is , Don't scan all indexes .


(6)index
appear index yes sql The index is used, but it is not used to filter through the index , Generally, the overlay index is used or the index is used for sorting and grouping .

(7)ALL
Full Table Scan, Will traverse the entire table to find the matching rows .

5.possible_keys
Show the indexes that may be applied to this table , One or more . If there is an index on the field involved in the query , Then the index will be listed , But different Must be queried for actual use .
6.key
Actual index used . If NULL, No index is used .
7.key_len
Represents the number of bytes used in the index , You can use this column to calculate the length of the index used in the query . key_len Field can help you check whether it is sufficient Using the index .ken_len The longer the , Explain that the more fully used the index .

8.ref
Shows which column of the index is used , If possible , It's a constant . Which columns or constants are used to find values on index columns .

9.rows
rows Columns show MySQL The number of rows that it must check to execute the query . The less, the better. !

10.Extra
Additional important information .
Focus on :
- Using filesort
- Using temporary
(1)Using filesort
explain mysql Will use an external index to sort the data , Instead of reading in the order of the indexes in the table .MySQL Index cannot be used in The sort operation completed is called “ File sorting ”.
appear filesort The situation of :

After optimization , No more filesort The situation of :
Create a composite index :idx_deptno_ename(deptno.ename)

Fields sorted in the query , If the sorting field is accessed by index, the sorting speed will be greatly improved .
(2)Using temporary
Use temporary table to save intermediate results ,MySQL Use temporary tables when sorting query results . It is common in sorting order by And group queries group by.
Before optimization :

After optimization :
Create a composite index :idx_deptno_ename(deptno,ename)

(3)Usingindex
Yes Using index Is a good thing
Using index The representative represents the corresponding select The override index is used in the operation (Covering Index), Avoid accessing the data rows of the table , Good efficiency !
If it appears at the same time using where, Indicates that the index is used to perform index key value lookups ; If not at the same time using where, Indicates that the index is just Used to read data instead of using an index to perform a lookup .
Sort or group by index .
(4)UsingWhere
Indicates that where Filter .
(5)Usingjoin buffer
Connection caching is used

(6)impossible where
where The value of the clause is always false, Can't be used to get any tuples .
(7)select tables optimized away
In the absence of GROUPBY In the case of clause , Index based optimization MIN/MAX Operation or for MyISAM Storage engine optimization COUNT(*) fuck do , You don't have to wait until the execution phase to do the calculation , The query execution plan generation phase completes the optimization .
边栏推荐
- C simple understanding - arrays and sets
- Aggregation analysis of research word association based on graph data
- [azure data platform] ETL tool (8) - ADF dataset and link service
- Implode and explode in golang
- 产品需求文档如何编写
- Parallel one degree relation query
- Get to know druid IO real time OLAP data analysis storage system
- English grammar_ Frequency adverb
- Differences of several query methods in PDO
- How to Draw Useful Technical Architecture Diagrams
猜你喜欢

Feign based remote service invocation

MySQL learning summary Xi: detailed explanation of the use of stored procedures and stored functions

Sparksql of spark

Peking University HP financial index - matching enterprise green innovation index 2011-2020: enterprise name, year, industry classification and other multi indicator data

在JDBC连接数据库时报错:Connection to 139.9.130.37:15400 refused.

To resolve project conflicts, first-class project managers do so

Prefecture level city - air flow coefficient data - updated to 2019 (including 10m wind speed, boundary height, etc.)

Carbon neutralization & Patent Innovation: multi indicator data such as patent panels (original documents) of provinces, cities and counties, and the number of low-carbon patents authorized

Unified scheduling and management of dataX tasks through web ETL

Panel data set of rural cities and towns: per capita consumption and expenditure of prefecture level cities 2012-2019 & rural data of provinces 2013-2019
随机推荐
Transaction processing in PDO
MySQL learning summary 6: data type, integer, floating point number, fixed-point number, text string, binary string
[azure data platform] ETL tool (7) - detailed explanation of ADF copy data
Coal industry database - coal price, consumption, power generation & Provincial Civil and industrial power consumption data
C method parameter: out
Video playback has repeatedly broken 1000w+, how to use the second dimension to create a popular model in Kwai
brew工具-“fatal: Could not resolve HEAD to a revision”错误解决
Implode and explode in golang
DTCC | 2021 China map database technology conference link sharing
MySQL learning summary 9: non empty constraints, uniqueness constraints, primary key, auto_ Increment, foreign key, default, etc
Spark Foundation
Level II C test skills
测试写入mysql数据300W条,每次1.6-2W之间就断掉然后出现以下问题:
The use of curl in PHP
Prefecture level city - air flow coefficient data - updated to 2019 (including 10m wind speed, boundary height, etc.)
Nuggets new oil: financial knowledge map data modeling and actual sharing
Isolation level, unreal read, gap lock, next key lock
Filters in PHP
MySQL imports and exports multiple libraries at one time
C simple understanding - generics