Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ChuChencheng opened this issue Jun 13, 2023 · 0 comments
Open

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

ChuChencheng opened this issue Jun 13, 2023 · 0 comments

Comments

@ChuChencheng
Copy link
Owner

背景

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

原因

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 ,都不会影响返回顺序了。

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant