ChuChencheng / note

菜鸡零碎知识笔记
Creative Commons Zero v1.0 Universal
3 stars 0 forks source link

MySQL 分页查询出现数据重复的问题及修复 #49

Open ChuChencheng opened 1 year ago

ChuChencheng commented 1 year ago

背景

分页查询某个表,发现有某些数据在不同的分页中都有出现,对应地,导致有些数据在哪一页都查不到。

原因

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 的列中,如果有相同值的行,这些行返回的顺序是随机的,不确定的。 影响执行计划的其中一个因素就是 Limit ,在分页的场景中。

在我遇到的问题里,接口是按照更新时间排序的,而那张表之前被刷写过,导致出现了大量相同更新时间,因此本来较小概率的事情就很容易出现了。

解决

If it is important to ensure the same row order with and without LIMIT, include additional columns in the ORDER BY clause to make the order deterministic.

如果要保证返回的顺序,可以多加一个排序的列,最好是数据不重复的列,保证所有排序的列组合起来类似一个唯一键,这样无论是否有 Limit ,都不会影响返回顺序了。

参考