V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
a33291
V2EX  ›  问与答

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

  •  
  •   a33291 · 23 天前 · 611 次点击
    相同版本数据库: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 字段的排序结果吗?
    3 条回复    2024-05-26 11:23:54 +08:00
    Tacks
        1
    Tacks  
       23 天前
    改成这个呢 `SELECT Id, Name, Order FROM test ORDER BY Order, Id;`

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

    现在我们没有特别在意字段和关键字重复的情况,因为大部分时候都是 orm 自动生成的标准 sql,不会造成错误或者冲突
    Tacks
        3
    Tacks  
       22 天前
    ```
    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 列中有多个行具有相同的值,则服务器可以自由以任何顺序返回这些行,并且根据整体执行计划的不同,返回值可能会有所不同。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3108 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:53 · PVG 19:53 · LAX 04:53 · JFK 07:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.