MySQL组合索引的设计与使用技巧

Time:2016/08/31 21:16:50   Click:


针对


select * from table where col1 > number order by col2 desc。

其实按照常规的方法可以这样设计:key(col1, col2)

但 是这种办法在mysql里不算是理想的,where条件里限定索引前部分是一个范围的情况下后面的order by还是会有filesort。

如果where条件里限定索引前部分是一个常量,那么order by就会有效利用索引。

例如:

select * from table where col1 = number order by col2 desc,

explain的结果就不错。

为了让它能够利用上索引并且消除filesort,可以这样设计
索引:key(col2,col1);


select * from table where col2 > min_value and col1 > number order by col2 desc;


这里where条件里同时执行了索引的两个列,并且为了保证逻辑一致,对col2列的限定条件等效于无限定。

这样mysql就能很好的利用索引了。这个技巧在mysql high performance2里也有提过




TAG
TOP

四川尚狐网络@2012 版权所有
蜀ICP备12016524号-2

立即咨询
成都网站建设,成都做网站,四川尚狐网络
40f13d50b73e104f832ed1b719ae6935