当前位置:网站首页>MySQL uses explain to analyze SQL execution plans to help find performance bottlenecks
MySQL uses explain to analyze SQL execution plans to help find performance bottlenecks
2022-07-24 08:02:00 【Procedural ape (siege lion)】
When sql Execution time exceeded expectations ( It usually takes longer than expected ) when , Or want to know sql Execute whether to use the index of the design , Or hope to know the optimized sql Whether optimization processing is carried out as expected during execution , You can use explain Command view sql Implementation plan of .
The way to use it is in mysql Command the terminal to execute sql Add... Before the statement explain command .
mysql> explain select * from shard_bill where pay_status='0' and merchant_no='123' ;
+----+-------------+-------------------+------------+------+------------------------------+-------------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------------------+------------+------+------------------------------+-------------+---------+-------+------+----------+-------------+
| 1 | SIMPLE | shard_bill | NULL | ref | merchant_no,merchant_no_date | merchant_no | 99 | const | 1 | 10 | Using where |
+----+-------------+-------------------+------------+------+------------------------------+-------------+---------+-------+------+----------+-------------+
1 row in setThe meaning of each column of data returned by the command execution is described below :
1. id
sql Sequence identification ,SQL From big to small execution .
- 1. id Phase at the same time , The order of execution is from top to bottom
- 2. If it's a subquery ,id The serial number of will increase ,id The higher the value, the higher the priority , The first to be executed
- 3.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 , Execute first
2. select_type
Show each... In the query select The type of clause
- (1) SIMPLE( Simple SELECT, Don't use UNION Or subquery, etc )
- (2) PRIMARY( If the query contains any complex sub parts , The outermost select Marked as PRIMARY)
- (3) UNION(UNION The second or later of SELECT sentence )
- (4) DEPENDENT UNION(UNION The second or later of SELECT sentence , Independent of external queries )
- (5) UNION RESULT(UNION Result )
- (6) SUBQUERY( First in subquery SELECT)
- (7) DEPENDENT SUBQUERY( First in subquery SELECT, Independent of external queries )
- (8) DERIVED( Derived from table SELECT stay FROM A subquery of a clause )
- (9) UNCACHEABLE SUBQUERY( The result of a subquery cannot be cached , The first line of the outer link must be reevaluated )
3. table
- When the value is the table name , Indicates which table to query data from ;
- The value is the alias of the table , An alias is specified for the table when querying ;
- null Indicates that table query is not required ;
4. type
Common types are :ALL, index, range, ref, eq_ref, const, system, NULL( From left to right , Performance from poor to good ).
- ALL:Full Table Scan,MySQL Will traverse the entire table to find the matching rows , Scan the whole table row by row , Usually , Minimum efficiency ;
- index: Full Index Scan,index And ALL The difference for index Type only traverses the index tree , amount to data_all index Scan all inodes , amount to index_all;
- range: Retrieve only rows in the given range , Use an index to select rows , Can scan the range according to the index ;
- ref: Represents the join matching condition of the table , That is, which columns or constants are used to find values on index columns , Through the index column , It can be directly referenced to some data rows ;
- eq_ref: similar ref, The difference is that the index used is the only index , For each index key value , Only one record in the table matches , Simply speaking , It is used in multi table connection primary key perhaps unique key As a condition of Association ;
- const、system: When MySQL Optimize some part of the query , And convert to a constant , Use these types to access . For example, place the primary key in where In the list ,MySQL You can convert the query to a constant ,system yes const Special case of type , When the query table has only one row , Use system;
- NULL: MySQL Decompose statements during optimization , Execute without even accessing tables or indexes , For example, selecting the minimum value from an index column can be done through a separate index search ;
- const、system、NULL Refers to query optimization to constant level , You don't even need to find time .
5. possible_keys
The system estimates several possible indexes , But in the end, it can only be used 1 individual .
- Pointed out that MySQL Which index can be used to find records in the table , If there is an index on the field involved in the query , Then the index will be listed , But not necessarily used by queries ;
- This column is completely independent of EXPLAIN Output the order of the table shown . This means that possible_keys Some of the keys in cannot actually be used in the order of the generated tables .
- If the column is NULL, There is no relevant index . under these circumstances , It can pass the inspection WHERE Clause to see if it references certain columns or columns suitable for indexing to improve your query performance .
6. Key
Show MySQL The index actually decided to use .
If index is not selected , The key is NULL. To coercive MySQL To use or neglect possible_keys Index in column , Use in query FORCE INDEX、USE INDEX perhaps IGNORE INDEX.
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 The displayed value is the maximum possible length of the index field , It's not the actual length , namely key_len It is calculated according to the table definition , It is not retrieved from the table )
Without loss of accuracy , The shorter the length, the better ;
8. ref
Indicates the join matching condition of the above table , That is, which columns or constants are used to find values on index columns .
9. rows
MySQL According to table statistics and index selection , Estimated number of rows to read to find the required record ;
10. filtered
The row of the returned result accounts for the row to be read (rows The value of the column ) Percent of .
11. Extra
Performance from good to bad :useing index>usinh where > using temporary | using filesort
This column contains MySQL Solve query details , There are several situations :
- Using temporary: Express MySQL You need to use temporary tables to store result sets , Common in sorting and grouping queries ;
- Using filesort:MySQL The sort operations that can't be done with indexes in are called “ File sorting ”;
- Using where: Column data is returned from a table that uses only the information in the index without reading the actual rows , This happens when all the request columns of the table are part of the same index , Express mysql The server will filter the rows after the storage engine retrieves them ;
- Using join buffer: This value emphasizes that the index is not used when getting the join condition , And you need to connect buffers to store intermediate results . If this value appears , That should pay attention to , Depending on the specific situation of the query, you may need to add indexes to improve the performance ;
- Impossible where: This value emphasizes where Statement will result in no eligible rows ;
- Select tables optimized away: This value means only by using the index , The optimizer may only return one line from the aggregate function result ;
- using index Represents index coverage , That is, the column of the query is right in the index , There is no need to return to the physical line to query data .
12. EXPLAIN Deficiency
- EXPLAIN I won't tell you about triggers 、 The impact of stored procedure information or user-defined functions on queries ;
- EXPLAIN Don't think about all kinds of Cache;
- EXPLAIN Can't show MySQL Optimizations done when executing queries ;
- Some of the statistics are estimated , Not exactly ;
- EXPALIN Can only explain SELECT operation , Other operations need to be rewritten as SELECT Then check the execution plan .
13. Actually execute and view sql execution time
explain What is provided is only a general implementation plan , It is not the actual implementation effect , This is in most cases , Can reflect sql Whether the statement is insufficient . If you want to know sql The actual execution time , You can use the following method .
mysql> show variables like "profiling";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| profiling | OFF |
+---------------+-------+
1 row in set
mysql> set profiling = 1;
Query OK, 0 rows affected
mysql> show variables like "profiling";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| profiling | ON |
+---------------+-------+
1 row in set
mysql> select * from boss_shard_bill_6 where bill_no='123' and pay_status='0' limit 10;
Empty set
mysql> show profiles;
+----------+-----------+------------------------------------------------------------------------------------+
| Query_ID | Duration | Query |
+----------+-----------+------------------------------------------------------------------------------------+
| 3 | 0.0017015 | select * from boss_shard_bill_6 where bill_no='123' and pay_status='0' limit 10 |
+----------+-----------+------------------------------------------------------------------------------------+
3 rows in set
mysql> set profiling = 1;
Query OK, 0 rows affectedBy setting profiling Parameters , This parameter is usually set in the debugging or testing environment , Because this parameter decreases to a certain extent mysql Efficiency of execution , It is not suitable to enable this parameter in the production environment .
边栏推荐
- Hcip day 10 notes
- 我在微软的这六个月
- Install librosa using Tsinghua image
- Decision tree - ID3, C4.5, cart
- Use of ArrayList
- JMeter stress test index interpretation
- Robot operation continuous learning thesis (1) original text reading and Translation -- primitive generation strategy learning without catastrophic forgetting in robot operation
- Hcip 13th day notes
- Intelligent robots and intelligent systems (Professor Zheng Zheng of Dalian University of Technology) -- 1. robots and mobile robots
- *Code understanding * common function parsing in pytoch
猜你喜欢

Image feature SIFT (scale invariant feature transform)

33 introduction to sparksql, dataframe and dataset

我在微软的这六个月
![[linear algebra] deeply understand matrix multiplication, symmetric matrix, positive definite matrix](/img/0f/4b7e92c61814b39e9b0448c0c854ee.png)
[linear algebra] deeply understand matrix multiplication, symmetric matrix, positive definite matrix

33-SparkSql的介绍、DataFrame和DataSet

Project practice - document scanning OCR recognition

JMeter stress test index interpretation

Train-clean-100 dataset

生成模型与判别模型
![[matlab] (III) application of MATLAB in Higher Mathematics](/img/ff/72b13fb597d5bdf3a989dd86cb6888.png)
[matlab] (III) application of MATLAB in Higher Mathematics
随机推荐
Generative model and discriminant model
Autojs article proficient in detailed explanation of autojs script tutorial
Digital twin demonstration project -- Talking about simple pendulum (2) vision exploration and application scenarios
Collection of sorting topics
Typescript double question mark operator
33 introduction to sparksql, dataframe and dataset
Collection of linked list topics
Simple Gateway - intranet server safely obtains external network data
Anaconda cannot shut down the method of forced shutdown
Continuous learning, lifelong learning, episodic memory, memory module paper summary -- gradient episodic memory promotes continuous learning
赛宁TechTalk丨攻防演练:攻击组合拳 “稳准狠”渗透
SIFT feature point extraction
Default risk early warning preliminary competition scheme of bond issuing enterprises [AI competition]
The growth path of software testing
Vidar-Team战队专访:AS WE DO, AS YOU KNOW.
News topic classification task -- tochtext library for text classification
Thesis reading: geotransformer
rbm 对比散度
Jetson AgX Orin source change
Use JMeter to analyze and test the lottery probability of the lottery interface