记一次MySQL order by 踩坑记录

20-10-31 10:58 字数 478 阅读 1021 已编辑

需求

分页+排序

表结构

表索引

表行数

1000万+

事故重现

原SQL

SELECT * FROM clearplate_users_log WHERE state = 3 ORDER BY create_time ASC LIMIT 0,100;

explain分析如下

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分析如下

explain结果

发现用到了 where 的 state 索引。

最后执行时间为0.3s。

分析

分析 type、ref、Extra 可以看出order by create_time效率很低。关键是为什么呢,order by 非主键的字段,发现 order by 的字段的优先级比 where 字段的优先级高。

附录

explain各项含义

explain

1人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论
站长 @ 十七度
文章
380
粉丝
23
喜欢
191
收藏
31
排名 : 1
访问 : 128.25万
私信