现在的位置: 首页 > 综合 > 正文

mysql索引的一个技巧

2017年12月06日 ⁄ 综合 ⁄ 共 468字 ⁄ 字号 评论关闭

 

针对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里也有提过.

抱歉!评论已关闭.