对于 `select * from table where col1 > number order by col2 desc` 这类查询,常规做法是建联合索引 key(col1, col2),但这在 MySQL 中并不理想:当 where 条件限定索引前部分是一个范围时,后面的 order by 依然会走 filesort;只有当前部分是常量时(如 col1 = number),order by 才能有效利用索引。
要消除 filesort,可以反向设计索引 key(col2, col1),并把查询改写为 `select * from table where col2 > min_value and col1 > number order by col2 desc`。这样 where 条件同时约束了索引的两列,其中对 col2 的限定条件等效于无限定(min_value 取足够小),从而保证逻辑一致。如此一来 MySQL 就能很好利用索引、避免 filesort。这个技巧在《High Performance MySQL》第二版中也有提及。