Ecstore/BBC mysql解决分页时数据错乱重复

问题:项目开发中遇到一个奇怪问题,测试站商品按照销量排序时,同一个商品出现了两次;按照ID排序就不会出现

原因:仔细阅读官方文档

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.(官方文档)

简而言之:mysql有一个特性,如果order by的字段不是unique的,即有值相同的行,那么这些数据的返回顺序是未定的,这是由于msyql做排序的时候并不能保证相同的值的相对顺序是一直不变的,这样两次查询由于数据的顺序未定,导致了一行数据出现在了两页中,mysql官方有相关讨论,这是mysql的一个特性,而不是bug(翻译不好,借鉴:https://blog.csdn.net/hyk_lk/article/details/78554004)

解决:order by 后面多个排序字段,排序的字段在表中最好是唯一的

发布了36 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/m0_37826705/article/details/84655644