优化order by 语句

mysql 演示数据库:http://downloads.mysql.com/docs/sakila-db.zip

mysql 中排序方式


 

 

有序索引顺序扫描直接返回有序数据

 

explain select customer_id from customer order by store_id\G;

 

这种方式在使用explain分析查询的时候显示为Using Index,不需要额外的排序,效率较高。

 

 

 

Filesort排序

所有不是通过索引直接返回排序结果的排序都叫Filesort排序

 

explain select * from customer order by store_id\G;

 

 

这种方式在使用explain分析查询的时候显示为Using filesort,

 

 

优化目标

尽量减少额外的排序,通过索引直接返回有序数据

1--where条件与order by 使用相同的索引
2--order by 的顺序和索引顺序相同
3--order by的字段都是升序或者都是降序

 

使用到索引的情况

select * from tablenamae order by key_part1,key_part_part2,.....;
select * from tablename where key_part1=1 order by key_part1 desc ,key_part2 desc;
select * from tablename order by key_part1 desc ,key_part2 desc;

 

不使用索引的情况

select * from tablename order by key_part1 desc ,key_part2 asc;
select * from tablename where key2=contant order by key1;
select * from tablename order key1,key2;
posted @ 2017-06-28 21:08  心碎whn  阅读(393)  评论(0编辑  收藏  举报