N times the efficiency 19 MySQL optimization cheats

A, EXPLAIN

MySQL optimization to do, we have to make good use of EXPLAIN view SQL execution plan.

Let's a simple example, labeling (1,2,3,4,5) we want to focus on data
http://img.blog.itpub.net/blog/2019/06/06/c4a6c6a3a9b253b3.jpeg?x Process-style = -oss / BB
type column, the type of connection. At least one good sql statement to achieve the range level. Prevent the emergence of all levels

The key column, use the name of the index. If you do not select an index, the value is NULL. The index may take enforcement side

key_len column index length

rows columns, the number of scanning lines. This value is an estimate

extra columns detail. Note that common values ​​are not very friendly: Using filesort, Using temporary

Second, the value contained in the SQL statement should not be overloaded IN

For MySQL made the corresponding optimized IN, IN upcoming constants in all stored in an array inside, and the array is sorted. However, if the value is more, consume generated is relatively large. Another example: select id from t where num in (1,2,3) for successive values, can not use in the between; used to replace or re-connected.

Three, SELECT statement is sure to specify the name of the field

SELECT * increase the number of unnecessary consumption (cpu, io, memory, network bandwidth); increases the possibility of using a covering index; and when the table structure changes, need to update before breaking. So I requested directly connected to the back of the field names in the select.

Fourth, when you need only one data use limit 1

This is to achieve the type column in EXPLAIN const type

Fifth, if the sort field is not used in the index, as little as possible to sort

Sixth, if restrictions in other fields are not indexed, or as little as possible

or both sides of the field, if there is not a field index, while other conditions are not indexed field, the situation will cause the query does not go indexes. Many times using union all or union (when necessary) way to replace "or" will get better results.

Seven, try to replace the union with the union all

Union and union all differences are mainly the former requires the collection of the results and then uniqueness of the filtering operation, which will involve sorting, increase the number of CPU operations, increase resource consumption and latency. Of course, with the proviso that two union all the result data set is not repeated.

Eight, do not use ORDER BY RAND ()

from ID SELECT dynamicOrder by RAND () limit 1000;
above sql statement, may be optimized for

select id from dynamic t1 join (select rand() * (select max(id) from dynamic) as nid) t2 on t1.id > t2.nidlimit 1000;
九、区分in和exists, not in和not exists

select * from table A where id in (select id from table B)
above sql statement corresponds

SELECT from Table exists WHERE A (SELECT from Table B where Table B.id = Table A.id)
distinguish between in and exists mainly caused a change in the drive sequence (which is the key property change), and if exists, then the outside layer table-driven table is accessed first, if it is IN, it runs the subquery. IN adapted so large and small outer inner case; EXISTS adapted to the outer case of the small and large table.

About not in and not exists, we recommended not exists, not only efficiency, not in logic there may be a problem. How to write a highly efficient alternative not exists sql statement?

Original sql statement

select colname ... from A table where a.id not in (select b.id from B tables)
efficiently sql statement

select colname ... from A Table Left join B table on where a.id = b.id where b.id is null
result set as shown below represents taken, A is not in the data table in Table B
http: //img.blog.itpub .net / blog / 2019/06/
06 / dc8c365a3363300d.jpeg? x-oss-process = style / bb ten, the use of reasonable methods to increase the efficiency of pagination pagination

select id, name from product limit 866613 , 20
when using the sql statement to do pagination, some people may find that, with the increasing amount of table data, use direct query page limit will become slower.

Optimization method is as follows: id may be taken before a maximum number of rows, and the next start point is limited based on this maximum id. So the column than the largest previous id is 866612. sql can be written as follows:

select id, name from product where id > 866612 limit 20
XI query segment

In some user selection page, some users may select the time frame is too large, resulting in a slow query. The main reason is the excessive number of scanning lines. This time can be programmed, segmentation query, loop through the results consolidation process on display.

The figure below sql statement, more than the number of scanning lines to one million when you can use segmentation query
http://img.blog.itpub.net/blog/2019/06/06/143fa863498d3a9c.jpeg?x-oss -process = style / bb
XII avoid a null value fields in the where clause determines

For null judgment will cause the engine to give up using the index and full table scan.

XIII is not recommended to use the% prefix fuzzy queries
Zhengzhou flow of the hospital: https://myyk.familydoctor.com.cn/21521/
such as LIKE "% name" or LIKE "% name%", such a query can lead to failure while the index a full table scan. But you can use LIKE "name%".
How that query% name%?
As shown below, although the index is added to the secret field, but did not explain the results in fruit
http://img.blog.itpub.net/blog/2019/06/06/b899901bd50e232c.jpeg?x-oss-process = style / bb
so how to solve this problem, the answer: use the full-text index

In our queries often use the select id, fnum, fdst from dynamic_201606 where user_name like '% zhangsan%';. Such a statement, the general index is unable to meet the needs of the inquiry. Fortunately, in MySQL, full-text indexing to help us.

Create a full-text index sql syntax is:

TABLE the ALTER dynamic_201606the ADD FULLTEXT INDEX idx_user_name( user_name);
using a full-text index sql statement is:

select id, fnum, fdst from dynamic_201606 where match (user_name) against ( 'zhangsan' in boolean mode);
Note: Before you need to create a full-text index, please contact the DBA to determine whether created. Also of note is the difference between the wording of the query with a regular index

Fourth, avoid operating in fields where clause expression

such as

select user_id, user_project from user_base where age * 2 = 36;
in the field of arithmetic operations on the line, which can cause the engine to give up using the index, the proposed change

select user_id, user_project from user_base where age = 36/2;
fifteen avoid implicit type conversion

Type column appears in the where clause field and passed when the type of occurrence inconsistent parameters of type conversion, it is recommended to determine the parameters of the type where

XVI for the joint index, the most left-prefix to comply with the law

For column contains fields for index id, name, school, id field can be directly used, may be id, name in this order, but the name; school can not use this index. Therefore, when creating the joint index must pay attention to the order of the index fields, commonly used in the query field on the front

XVII force index can be used, if necessary, to force an index query go

Sometimes MySQL optimizer to take it considers appropriate index to retrieve the sql statement, but it may be used in the index is not what we want. Then you can use forceindex to force the optimizer to use the index we have developed.

XVIII attention span query

For the joint index, if there is range queries, such as between,>, <when ​​other conditions, can cause failure of the back of the index field.

Ninth, on JOIN optimization
http://img.blog.itpub.net/blog/2019/06/06/bd94cb4f6032e868.jpeg?x-oss-process=style/bb
LEFT JOIN A table-driven table

INNER JOIN MySQL will automatically identify the role of the little data table-driven table
RIGHT JOIN B is a table-driven table
Note: MySQL is not full join, you can use the following ways to solve
the SELECT from the Join A left B = ON b.name A.namewhere iS nullunion allselect b.name from B;
to make use of inner join, left join to avoid
participation in the joint table queries of at least two tables, there is generally the size of the points. If the connection is inner join, MySQL will automatically choose a small table in the absence of other filters situation as the driving table, but left join followed in the choice of driving table is the principle of the left drive to the right, that left join the table name on the left driven table.
Rational use of the index
to be driven on the table index field as a limit field.
With a small table to drive a large table

From the diagram can be directly see if it is possible to reduce the drive table, reduce the number of nested loops in the loop, to reduce the number and the total amount of CPU IO operations.

巧用STRAIGHT_JOIN

inner join is selected by the driver mysql table, but there are some special circumstances need to select another table as the driving table, such as a group by, order by, etc. "Using filesort" when "temporary Using." STRAIGHT_JOIN to force the join order, in the table is the driving table STRAIGHT_JOIN left, the right is being driven table. In use STRAIGHT_JOIN there is a proviso that the query is an inner join, is the inner join. Other links are not recommended STRAIGHT_JOIN, or it may cause inaccurate results.
http://img.blog.itpub.net/blog/2019/06/06/33cb3ce37f874c33.jpeg?x-oss-process=style/bb

Guess you like

Origin blog.51cto.com/14339031/2406425