mysql explain

The explain shows how MySQL uses indexes to process select statements and join tables. Can help choose better indexes and write more optimized query statements.

First parse a sql statement to see what appears

EXPLAINSELECTs.uid,s.username,s.name,f.email,f.mobile,f.phone,f.postalcode,f.address
FROM uchome_space ASs,uchome_spacefieldASf
WHERE 1 
AND s.groupid=0
AND s.uid=f.uid

1. id

SELECT identifier. This is the SELECT query sequence number. This is not important, the query sequence number is the order in which the sql statement is executed, see the following sql

EXPLAINSELECT*FROM(SELECT* FROMuchome_space LIMIT10)ASs

Its execution result is

You can see that the id has changed at this time.

2.select_type

select type, it has the following values

2.1 simple It represents a simple select without union and subqueries

2.2 The outermost select of primary, in the statement with sub-query, the outermost select query is primary, which is the case in the above figure

2.3 union The second or the latter one of the union statement. Now execute a statement, explain 
select * from uchome_space limit 10 union select * from uchome_space limit 10,10

will result in the following

The second statement uses union

2.4 The second or subsequent SELECT statement in the dependent union UNION, depending on the outer query

2.5 union result The result of UNION, as shown above

There are a few more parameters, I won't talk about it here, it's not important

3 table

The table used for the output row, this parameter is obvious and easy to understand

4 type

Connection Type. There are multiple parameters, it is important and difficult to introduce from the best type to the worst type first 

4.1 system

There is only one row in the table, which is a special column of const type, which does not usually appear, and this can also be ignored.

4.2 const

The table has at most one matching row, and const is used to compare the primary key or unique index. Because only one row of data is matched, it is very fast

Remember that the primary key or unique must be used, and it will be const only when two pieces of data are retrieved, see the following statement

explain SELECT * FROM `asj_admin_log` limit 1, the result is

Although only one piece of data is searched, because the specified index is not used, const will not be used. Continue to look at the following

explain SELECT * FROM `asj_admin_log` where log_id = 111

log_id is the primary key, so const is used. So it can be understood that const is the most optimized

4.3 eq_ref

For the interpretation of eq_ref, the mysql manual says this: "For each combination of rows from the preceding table, read a row from this table. This is probably the best join type, except for the const type. It is used in a All parts of the index are used by joins and the index is UNIQUE or PRIMARY KEY". eq_ref can be used to compare indexed columns using =. see the following statement

explain select * from uchome_spacefield,uchome_space where uchome_spacefield.uid = uchome_space.uid

The result obtained is shown in the figure below. Apparently mysql uses eq_ref joins for uchome_space table.

Current questions:

       4.3.1 Why is eq_ref used in only one table of uchome_space, and if the sql statement becomes

       explain select * from uchome_space,uchome_spacefield where uchome_space.uid = uchome_spacefield.uid

       The result is still the same, it should be noted that uid is primary in both tables

4.4 ref For each combination of rows from the preceding table, all rows with matching index values ​​will be read from this table. Use ref if the join uses only the leftmost prefix of the key, or if the key is not a UNIQUE or PRIMARY KEY (in other words, if the join cannot select a single row based on the key). This join type is good if the keys used match only a few rows.

Look at the following statement explain select * from uchome_space where uchome_space.friendnum = 0, the result is as follows, this statement can find 1w pieces of data

4.5 ref_or_null This join type is like ref, but with the addition that MySQL can specifically search for rows containing NULL values. This join type optimization is often used in solving subqueries.

The above five cases are all ideal index usage cases.

4.6 index_merge This join type indicates that the index merge optimization method is used. In this case, the key column contains the list of used indexes, and key_len contains the longest key element of the used indexes.

4.7 unique_subquery 

4.8 index_subquery

4.9 range Search within a given range, using an index to examine rows. Look at the following two sentences

explain select * from uchome_space where uid in (1,2)

explain select * from uchome_space where groupid in (1,2)

The uid has an index, and the groupid has no index. The result is that the join type of the first statement is range, and the second one is ALL. I thought it was a certain range, so it is obvious that a connection like between can also be used.

explain select * from uchome_space where friendnum = 17

Such a statement will not use range, it will use a better join type which is the ref introduced above

4.10 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. (That is to say, although all and Index both read the whole table, index is read from the index, and all is read from the hard disk)

MySQL can use this join type when a query uses only columns that are part of a single index.

4.11 ALL Performs a full table scan for each combination of rows from the previous table. This is usually not good if the table is the first table not marked const, and is usually bad in its case . Often more indexes can be added instead of using ALL so that rows can be retrieved based on constant values ​​or column values ​​in previous tables.

5 possible_keys  hint which index to use will find the row in this table, less important

6 keys  The index used by MYSQL is simple and important

7 key_len  Index length used by MYSQL

8 ref    The ref column shows which column or constant is used along with the key to select rows from the table.

9 rows  shows the number of rows MYSQL executes the query, simple and important, the bigger the value, the worse

10 Extra   This column contains details of the query being resolved by MySQL.

10.1 Distinct MySQL stops searching for more rows for the current row combination after finding the first matching row. I have never seen this value

10.2 Not exists  

10.3 range checked for each record

no suitable index found

10.4 using filesort    

The MYSQL manual explains it this way "MySQL needs an extra pass to figure out how to retrieve the rows in sorted order. This is done by going through all the rows according to the join type and saving the sort key and row pointer for all rows matching the WHERE clause Sort. Then the key is sorted, and the rows are retrieved in sorted order." Don't quite understand at the moment

10.5 using index Only use the information in the index tree without further searching to read the actual row to retrieve the information in the table. This is easier to understand, that is to say whether the index is used or not

explain select * from ucspace_uchome where uid = 1 extra is using index (uid has an index)

explain select count(*) from uchome_space where groupid=1 The extra is using where (groupid is not indexed)

10.6 using temporary

To resolve the query, MySQL needs to create a temporary table to hold the results. Typical cases are when a query contains GROUP BY and ORDER BY clauses that can list columns in different cases.

The appearance of using temporary means that the statement needs to be optimized, for example

EXPLAIN SELECT ads.id FROM ads, city WHERE   city.city_id = 8005   AND ads.status = 'online'   AND city.ads_id=ads.id ORDER BY ads.id desc

id  select_type  table   type    possible_keys   key      key_len  ref                     rows  filtered  Extra                          
------  -----------  ------  ------  --------------  -------  -------  --------------------  ------  --------  -------------------------------
     1  SIMPLE       city   ref     ads_id,city_id  city_id  4        const                   2838    100.00 Using temporary; Using filesort
     1  SIMPLE       ads     eq_ref  PRIMARY         PRIMARY  4        city.ads_id       1    100.00  Using where   

This statement uses using temporary, while the following statement does not

 

EXPLAIN SELECT ads.id FROM ads, city WHERE   city.city_id = 8005   AND ads.status = 'online'   AND city.ads_id=ads.id ORDER BYcity.ads_id desc

id  select_type  table   type    possible_keys   key      key_len  ref                     rows  filtered  Extra                      
------  -----------  ------  ------  --------------  -------  -------  --------------------  ------  --------  ---------------------------
     1  SIMPLE       city   ref     ads_id,city_id  city_id  4        const                   2838    100.00 Using where; Using filesort
     1  SIMPLE       ads    eq_ref  PRIMARY         PRIMARY  4        city.ads_id       1    100.00  Using where   

Why is this? The difference between them is just an order by. The algorithm for MySQL table association is Nest Loop Join, which uses the result set of the driving table as the basic data of the loop, and then passes the data in the result set as the filter condition to the next table one by one. Query the data, then combine the results. In the EXPLAIN result, the table in the first row is the driver table (Important!) The above two query statements, the driver table is city, as shown in the execution plan above!

The driving table can be sorted directly, and the non-driving table (field sorting) needs to sort the merged result (temporary table) of the loop query (Important!)
Therefore, when ordering by ads.id desc, it is necessary to use temporary first!
Definition of drive table
 In 2006, wwh999
concluded that when a multi-table join query is performed, the definition of [driven table] is: 1) When the join condition is specified, the table with few rows of records that satisfy the query condition is the [driven table];
2) No When specifying a join condition, the table with the fewest rows is the [driving table] (Important!).

Always drive large result sets with small result sets

 

I learned a very important point today: when we are not sure which type of join to use, let the mysql optimizer automatically judge, we only need to write select * from t1, t2 where t1.field = t2.field

10.7 using where

The WHERE clause is used to restrict which row matches the next table or is sent to the client. Unless you specifically fetch or check all rows from the table, the query may have some errors if the Extra value is not Using where and the table join type is ALL or index. (This explanation is not very understandable, because many, many statements will have where conditions, and the type of all or index can only indicate that there is a lot of retrieved data, and does not indicate an error. Using where is not very important, but it is very common)

If you want to make your query as fast as possible, you should find out the Extra values ​​for Using filesort and Using temporary.

10.8 Using sort_union(...), Using union(...),Using intersect(...)

These functions illustrate how to merge index scans for the index_merge join type

10.9 Using index for group-by

Similar to the Using index method of accessing a table, Using index for group-by means that MySQL has found an index that can be used to query all columns of a GROUP BY or DISTINCT query without additionally searching the hard disk to access the actual table. Also, use the index in the most efficient way so that for each group, only a few index entries are read.

Example explanation

 

By multiplying all the values ​​in the rows column of the EXPLAIN output, you can get a hint about how a join works. This should roughly tell you how many rows MySQL has to check in order to execute the query. This product is also used to determine which multi-table SELECT statement to execute when you limit the query with the max_join_size variable.

 

Source: http://blog.csdn.net/zhuxineli/article/details/70244831

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326569904&siteId=291194637