Mysql按时间排序分页问题 2018

Posted by Bink的博客 on December 5, 2018

Mysql按时间排序分页数据错误问题

问题抛出

最近使用Mysql查询数据遇到个奇葩的坑:在按时间排序进行分页的时候,遇见了这样的问题。 在查询所有的数据,并没有重复的数据出现,但是按时间排序,分页后有重复的数据。

案例重现如下

表结构如下:

查询表,并按date字段进行排序显示全部数据:

select * from test order by date;

查询第一页:

select * from test order by date limit 2 offset 0;

查询第二页:

select * from test order by date  limit 2 offset 2;

查询第三页:

select * from test order by date  limit 2 offset 4;

分析以上数据

通过上面的数据分析发现第一页第三页数据有重复,细心的你会发现在这张表中, 每行数据的date字段的值都是一样的,如果是不同的时间,不会出现按时间进行排序, 并分页的重复数据。由此,可以看出,如果时间相同的情况下,MySQL通过时间进行排序,并 进行分页查询数据的时候,会出现重复的数据的错误现象,同时还导致了第一条数据没有被显示出来。

解决问题

官方文档是这么说的:

If multiple rows have identical values in the ORDER BY columns, the server is 
free to return those rows in any order, and may do so differently depending on
the overall execution plan. In other words, the sort order of those rows is 
nondeterministic with respect to the nonordered columns.
One factor that affects the execution plan is LIMIT, so an ORDER BY query with 
and without LIMIT may return rows in different orders.

结合官档,我们知道 order by 排序的时候,如果排序字段中有多行相同的列值,则排序结果是不确定的。 我们可以先按照时间字段date进行排序,如果时间相同的情况下,再按照id或者其他的字段去联合排序, 那么就不会出现数据重复和丢失数据的问题了。