Optimize the order by statement:
In some cases, MySQL can use an index to satisfy the ORDER BY clause without requiring additional sorting. The where condition and order by use the same index, and the order of order by is the same as the index order, and the fields of order by are all in ascending or descending order.
For example: The following sql can use indexes.
SELECT * FROM t1 ORDER BY key_part1,key_part2,... ;
SELECT * FROM t1 WHERE key_part1=1 ORDER BY key_part1 DESC, key_part2 DESC;
SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 DESC;
But not in the following cases Use index:
SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;
--order by field mixed ASC and DESC
SELECT * FROM t1 WHERE key2=constant ORDER BY key1;
--keyword used to query rows It is different from what is used in ORDER BY
SELECT * FROM t1 ORDER BY key1, key2;
--Use ORDER BY for different keywords:
The above is the content of mysql optimization order by statement, please pay attention to more related content PHP Chinese website (m.sbmmt.com)!