需求
分页+排序
表结构
表行数
1000万+
事故重现
原SQL
SELECT * FROM clearplate_users_log WHERE state = 3 ORDER BY create_time ASC LIMIT 0,100;
explain分析如下
![]()
发现最后没用到 where 的 state 索引,用的是create_time索引,create_time为int类型时间戳。
最后执行时间为13.8s。
优化后的SQL
SELECT * FROM clearplate_users_log WHERE state = 3 ORDER BY id ASC LIMIT 0,100;
explain分析如下
![]()
发现用到了 where 的 state 索引。
最后执行时间为0.3s。
分析
分析 type、ref、Extra 可以看出order by create_time效率很低。关键是为什么呢,order by 非主键的字段,发现 order by 的字段的优先级比 where 字段的优先级高。
附录
explain各项含义

