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).
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
index use the Order By (2) Analysis
EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY age;
EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY age,birth;
EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY birth;
Produced filesort
EXPLAIN SELECT * FROM tblA WHERE age>20 ORDER BY birth,age;
Produced filesort
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:
Single Sort will be some problems, such as:
optimization strategy:
Why?
Finally, to a summary: