问题:项目开发中遇到一个奇怪问题,测试站商品按照销量排序时,同一个商品出现了两次;按照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 后面多个排序字段,排序的字段在表中最好是唯一的
本文解析了一个在项目开发中遇到的问题,即在使用MySQL进行商品销量排序时,同一商品出现重复显示的现象。通过深入研究官方文档,揭示了这一现象背后的原理:当ORDER BY字段存在相同值时,MySQL无法保证数据的稳定排序,尤其是在使用LIMIT的情况下。文章提供了解决方案,建议在ORDER BY后增加唯一性字段以确保排序稳定性。
1320

被折叠的 条评论
为什么被折叠?



