MySQL limit 翻页数据重复的问题

226 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第7天,点击查看活动详情

0.背景

Mysql版本:5.7

1.出问题原因

  在MySql5.6开始,limit加入了一个新特性:LIMIT Query Optimization。假设你写了这样一个sql:

select * from my_table limit 10,10;

  它是符合优化原则的:

MySQL sometimes optimizes a query that has a LIMIT row_count clause and no HAVING clause:

  纵览所有的优化原则,发现与我们最普通的情况有关系的也只有这一条:

If an index is not used for ORDER BY but a LIMIT clause is also present, the optimizer may be able to avoid using a merge file and sort the rows in memory using an in-memory filesort operation.

  意即:如果索引未用于ORDER BY,但也存在LIMIT子句,则优化器可能能够避免使用合并文件,并使用内存中文件排序操作对内存中的行进行排序。 再有和我们有点关系的可能也就是:

If you select only a few rows with LIMIT, MySQL uses indexes in some cases when normally it would prefer to do a full table scan.

  意即:如果您只需要查出几行,MySQL会因为避免全表扫描而在某些情况下使用索引。

  MySQL的优化规则很复杂,如果你不明确指定一个不重复的用于order by列,数据库并不保证每一次排序都是一致的,也就是说分页内容会出现重复的可能性。

我认同MySQL order by limit 分页数据重复问题中的观点:

分页是建立在排序的基础上,进行了数量范围分割。排序是数据库提供的功能,而分页却是衍生的出来的应用需求。

  故解决问题的方式就很明了了。

2.解决方法

select * from my_table order by id limit 10,10 ;

3.拓展阅读