Home > php教程 > php手册 > body text

MySQL手册版本 5.0.20-MySQL优化(四) (1)

WBOY
Release: 2016-06-13 10:06:51
Original
1088 people have browsed it

7.2.9 MySQL 如何优化 ORDER BY


在一些情况下,MySQL可以直接使用索引来满足一个 ORDER BY 或 GROUP BY 子句而无需做额外的排序。


尽管 ORDER BY 不是和索引的顺序准确匹配,索引还是可以被用到,只要不用的索引部分和所有的额外的 ORDER BY 字段在 WHERE 子句中都被包括了。下列的几个查询都会使用索引来解决 ORDER BY 或 GROUP BY 部分:


SELECT * FROM t1 ORDER BY key_part1,key_part2,... ;

SELECT * FROM t1 WHERE key_part1=constant ORDER BY key_part2;

SELECT * FROM t1 WHERE key_part1=constant GROUP BY key_part2;

SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 DESC;

SELECT * FROM t1

WHERE key_part1=1 ORDER BY key_part1 DESC, key_part2 DESC;

在另一些情况下,MySQL无法使用索引来满足 ORDER BY,尽管它会使用索引来找到记录来匹配 WHERE 子句。这些情况如下:


对不同的索引键做 ORDER BY :


SELECT * FROM t1 ORDER BY key1, key2;

在非连续的索引键部分上做 ORDER BY:


SELECT * FROM t1 WHERE key2=constant ORDER BY key_part2;

同时使用了 ASC 和 DESC:


SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;

用于搜索记录的索引键和做 ORDER BY 的不是同一个:


SELECT * FROM t1 WHERE key2=constant ORDER BY key1;

有很多表一起做连接,而且读取的记录中在 ORDER BY 中的字段都不全是来自第一个非常数的表中(也就是说,在 EXPLAIN 分析的结果中的第一个表的连接类型不是 const)。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template