# 分享一个关于解决Mysql limit分页在数据很多时的查询速度慢问题

**URL:** <https://www.shiqidu.com/t/topic/225>\
**Category:** 开发调优\
**Tags:** MySQL\
**Created:** [September 18, 2017, 7:41am UTC](https://www.shiqidu.com/t/topic/225 "2017-09-18T07:41:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
**Post date:** [September 18, 2017, 7:41am UTC](https://www.shiqidu.com/t/topic/225/1 "2017-09-18T07:41:39Z")

</div>

Limit 分页的语法大家都知道`limit offset rows`  
加入我有一张表有400+数据  
  
 ![d3719b2c10b5b38448a81c3cf64b6939.png](https://discourse.shiqidu.com/uploads_nj/article/20170918/d3719b2c10b5b38448a81c3cf64b6939.png)

我现在要做分页功能，我的sql是这样的

```auto
select xxx,xxx,xxx,from tablename where xxx,xxx,xxx order by xxx,xxx limit 15,15

```

假如在`where`条件下共有39条数据，我每页显示15条数据，那么第二页是`limit 15, 15`，第三页是`limit 30, 15`。  
我们大多情况下回直接这么写，因为我不知道最后一页应该有多少数据，所以我直接`limit {页码}, {每页显示数量}`。  
这样写在前两页是没有问题的，但是查到最后一页的时候会非常慢。  
经测试在前两页我的执行时间是 **0.5s** 之内，还能接受， 但是最后一页的执行时间却是`2m多`!!!  
怎么解决这一问题呢，经过我的摸索，我发现如果提前把最后一页的`rows`算出来，速度会非常快。  
比如在这个问题里最后一页的查询如果我们写成`limit 30, 9`，那么查询时间就大大缩减了。  
解决办法很简单，我们只需要拿着`where`方法把总数算一下，然后把`sql`处理下就行啦。
