# 记一次MySQL order by 踩坑记录

**URL:** <https://www.shiqidu.com/t/topic/725>\
**Category:** 开发调优\
**Tags:** MySQL\
**Created:** [2020 年10 月 31 日 02:58 UTC](https://www.shiqidu.com/t/topic/725 "2020-10-31T02:58:46Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2020 年10 月 31 日 02:58 UTC](https://www.shiqidu.com/t/topic/725/1 "2020-10-31T02:58:46Z")

</div>

### 需求

分页+排序

### 表结构

 ![表索引](https://discourse.shiqidu.com/uploads/default/original/1X/c5794975a2dc28a429a7174bb4272f2c51d52155.png)

### 表行数

1000万+

### 事故重现

#### 原SQL

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

```

#### explain分析如下

![explain结果](https://discourse.shiqidu.com/uploads/default/optimized/1X/da41c8b9cbabe00268fd2b123b97001fa3940be5_2_690x29.png)

发现最后没用到 where 的 state 索引，用的是create\_time索引，create\_time为int类型时间戳。

最后执行时间为13.8s。

#### 优化后的SQL

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

```

#### explain分析如下

![explain结果](https://discourse.shiqidu.com/uploads/default/optimized/1X/9a19b044734b1893c9deaec59b2b8742979288b1_2_690x31.png)

发现用到了 where 的 state 索引。

最后执行时间为0.3s。

### 分析

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

### 附录

explain各项含义

 ![explain](https://discourse.shiqidu.com/uploads/default/original/1X/016676e3425bd72efd421bed2d388fe53d11e4b0.jpeg)
