当前位置:网站首页>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 ?

  1. Read order of tables
  2. Operation type of data read operation
  3. Which indexes can be used
  4. Which indexes are actually used
  5. References between tables
  6. 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

concerns :id Number, each number , Represents an independent query . One sql The fewer query times, the better .

 

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 .

原网站

版权声明
本文为[TRX1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280529582717.html