比如这条语句,排序的字段 sync_timestamp 是有索引的,但是查询解析器就是用不到,
SELECT ue.id,ue.begin_time,ue.submit_time,ue.sync_timestamp,ue.score,ue.user_id,ue.server_id,e.logic_id
FROM t_user_exam ue
INNER JOIN t_exam e ON ue.exam_id=e.exam_id AND ue.sync_timestamp>1585581624344 AND e.client_id='guokao'
ORDER BY sync_timestamp
LIMIT 100;
用explain 后的效果
查询需要30秒钟
解决方法就是强制 mysql 使用指定索引
SELECT ue.id,ue.begin_time,ue.submit_time,ue.sync_timestamp,ue.score,ue.user_id,ue.server_id,e.logic_id
FROM t_user_exam ue FORCE INDEX (idx_sync_timestamp)
INNER JOIN t_exam e ON ue.exam_id=e.exam_id AND ue.sync_timestamp>1585581624344 AND e.client_id='guokao'
ORDER BY sync_timestamp
LIMIT 100;
这样就用到了索引,速度提高很明显