mysql 排序结果不一致的原因是啥?

32 天前
 a33291
相同版本数据库:mysql 8.0.28
部署方式: a:win server 2012 r2 b:rocky 9 docker
有表结构如下,表名: test,字符集 utf8mb4 排序规则 utf8mb4_general_ci
Id(int) Name(varchar) Order(int)

数据特性:
插入默认 10 条随机数据,但是 Order 均为 0

在数据库和表的字符集和排序规则均一致的情况,下列语句在 a/b 下输出顺序不同
select Id,Name,Order from test order by Order;

现象如下:
1. a 和 b 都执行这个语句,输出结果顺序不一致;
2. 分别在 a 或 b 上多次执行,结果相同,也就是说在实例内部结果是稳定的;

疑问如下
1. 首先,由于排序字段是 int,所以应和字符集以及排序规则无关吧?
2. 除了排序规则还有什么配置或者方式可以影响对一个 int 字段的排序结果吗?
694 次点击
所在节点    问与答
3 条回复
Tacks
32 天前
改成这个呢 `SELECT Id, Name, Order FROM test ORDER BY Order, Id;`

所有行的 Order 值都是 0 时,排序是不确定的。另外是你换个名字吧 order 这关键词被你当字段用。
a33291
31 天前
@Tacks 是的,解决方案我们也是这样处理.只是好奇为啥不一致,我意思他排序算法跨平台不稳定而且不可配置好像

现在我们没有特别在意字段和关键字重复的情况,因为大部分时候都是 orm 自动生成的标准 sql,不会造成错误或者冲突
Tacks
31 天前
```
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. Consider this query, which is sorted by the category column but nondeterministic with respect to the id and rating columns:
```

来自 https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html


简单来说 :如果在 ORDER BY 列中有多个行具有相同的值,则服务器可以自由以任何顺序返回这些行,并且根据整体执行计划的不同,返回值可能会有所不同。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1043854

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX