mysql排序ORDER BY Optimization
阿新 • • 發佈:2019-01-25
有的時候,MySQL不用額外的排序而是使用索引就能滿足order by操作。
即使order by不直接匹配索引,索引也能用到,只要所有未用到索引的部分和order by之外的索引列在where字句中,
下面的查詢order by部分使用到了索引
SELECT * FROM t1
ORDER BY key_part1,key_part2,... ;
SELECT * FROM t1
WHERE key_part1 = constant
ORDER 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;
SELECT * FROM t1
WHERE key_part1 > constant
ORDER BY key_part1 ASC;
SELECT * FROM t1
WHERE key_part1 < constant
ORDER BY key_part1 DESC;
SELECT * FROM t1
WHERE key_part1 = constant1 AND key_part2 > constant2
ORDER BY key_part2;
但是有的時候,MySQL不會使用索引來解決order by的問題,即使where條件已經用到索引
1.order by使用不同的索引
SELECT * FROM t1 ORDER BY key1, key2;
2.order by部分列非索引字首
SELECT * FROM t1 WHERE key2=constant ORDER BY key_part2;
3.升降序混合
SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;
4.獲取行的索引與order by部分不是同一個索引
SELECT * FROM t1 WHERE key2=constant ORDER BY key1;
5.order by列上有函式
SELECT * FROM t1 ORDER BY ABS(key);
SELECT * FROM t1 ORDER BY -key;
即使order by不直接匹配索引,索引也能用到,只要所有未用到索引的部分和order by之外的索引列在where字句中,
下面的查詢order by部分使用到了索引
SELECT * FROM t1
ORDER BY key_part1,key_part2,... ;
SELECT * FROM t1
WHERE key_part1 = constant
ORDER 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;
SELECT * FROM t1
WHERE key_part1 > constant
ORDER BY key_part1 ASC;
SELECT * FROM t1
WHERE key_part1 < constant
ORDER BY key_part1 DESC;
SELECT * FROM t1
WHERE key_part1 = constant1 AND key_part2 > constant2
ORDER BY key_part2;
但是有的時候,MySQL不會使用索引來解決order by的問題,即使where條件已經用到索引
1.order by使用不同的索引
SELECT * FROM t1 ORDER BY key1, key2;
2.order by部分列非索引字首
SELECT * FROM t1 WHERE key2=constant ORDER BY key_part2;
3.升降序混合
SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;
4.獲取行的索引與order by部分不是同一個索引
SELECT * FROM t1 WHERE key2=constant ORDER BY key1;
5.order by列上有函式
SELECT * FROM t1 ORDER BY ABS(key);
SELECT * FROM t1 ORDER BY -key;