MySQL index optimization (to sort)

MySQL optimization

General interview MySQL optimized answer ideas how to do:
1. First allow the system to run at least a day to see the system's slow SQL
2. Open the slow query log, set thresholds, such as more than five seconds is slow SQL, and catch it taken out
3.explain + slow SQL to analyze
4.show profile query SQL implementation details inside and MySQL server life cycle where
the parameter tuning 5.SQL database server

First, the optimization principle: a small table-driven large table, i.e. small data set to drive large data sets.

When B is set to be smaller than the data table A table of data set, than exists in a

SELECT * FROM A WHERE id IN (SELECT id FROM B);
等价于
SELECT * FROM A WHERE EXISTS (SELECT  1 FROM B WHERE B.id=A.id)

When the data set of Table A Table B must be less than the data set, than exists in a

EXISTS
SELECT ... FROM table WHERE EXISTS(subquery)

This syntax can be understood as: the main data query into subqueries some conditions are verified, to determine whether the data is preserved main query results based on the verification result (true / false).
Here Insert Picture Description

Two, Order By Optimization

1.ORDER BY clause, try to use index sort mode, sort FileSort avoid using
(1) establishing a table tblA, and create a composite index on age and birth field
Here Insert Picture Description
index use the Order By (2) Analysis

EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY age;

Here Insert Picture Description

EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY age,birth;

Here Insert Picture Description

EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY birth;

Here Insert Picture Description
Produced filesort

EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY birth,age;

Here Insert Picture Description
Produced filesort
Here Insert Picture Description
MySQL supports two ways of sorting, FileSort and Index, high efficiency index, which refers to the completion of ordering MySQL scanning the index itself, way less FileSort efficiency.

When the order by satisfying two cases, use the index sort by: 1.order by statements forefront of the most left index 2. Use the where clause and order by clause conditions combined to meet the leftmost forefront index.
As far as possible to complete a sort operation on the index column, follow the principle of the best left-prefix index established.
If not in the index column, filesort There are two algorithms, one-way and two-way sorting ordering:
Here Insert Picture Description
Single Sort will be some problems, such as:
Here Insert Picture Description
optimization strategy:
Here Insert Picture Description
Why?
Here Insert Picture Description
Finally, to a summary:
Here Insert Picture Description

Three, Group By optimizing

Here Insert Picture Description

Published 23 original articles · won praise 67 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_43395911/article/details/104370197