索引与排序

排序可能发生2种情况:

1: 对于覆盖索引,直接在索引上查询时,就是有顺序的, using index

2: 先取出数据,形成临时表做filesort(文件排序,但文件可能在磁盘上,也可能在内存中)

 

我们的争取目标-----取出来的数据本身就是有序的! 利用索引来排序.


表中有个index(cat_id, shop_price)联合索引:

image.png

这里没有用到sort file,因为cat_id本身排序好了,cat_id下的shop_price也是排序好的

image.png

而如果order by click_count则用到file sort了:

image.png

比如: goods商品表, (cat_id,shop_price)组成联合索引,

where cat_id=N order by shop_price ,可以利用索引来排序,

select goods_id,cat_id,shop_price from goods order by shop_price;

// using where,按照shop_price索引取出的结果,本身就是有序的.

 

select goods_id,cat_id,shop_price from goods order by click_count;

// using filesort 用到了文件排序,即取出的结果再次排序