mysql 不用orderby 某些情况下会乱序

2022-10-20 11:56:50

一 背景

  • 当我不传条件的时候,很正常的排序;
  • 传了条件,乱序了;

目前的直觉是,不传条件,以id为索引,自然而然的顺序得到结果; 传了条件,则以index索引,当中tree get数set数的时候,顺序没有保证了。不能确定是不是正确。

二 order by有相同,不能保证id排序

  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.
......
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. For example, if id values are unique, you can make rows for a given category value appear
in id order by sorting like this

     百度翻译:

如果多行的ORDER BY列中有相同的值,服务器可以按任意顺序返回这些行,并且

根据总体执行计划,可能会有不同的做法。换句话说,这些行的排序顺序是

关于非有序列的不确定性。

......

如果重要的是确保有限制和无限制的行顺序相同,请在order BY子句中包含其他列

使订单具有确定性。例如,如果id值是唯一的,则可以显示给定类别值的行

按这样的排序

三 结论

  • 无order 无条件, id主键升序
  • 无order 有条件(不确定是不是走索引情况),乱序
  • 有order,有相同值, 两值乱序
  • --- 养成+order的习惯,值不唯一可以orderby两个字段(order by id asc, ct desc)
  • 作者:布叔喂丶
  • 原文链接:https://blog.csdn.net/bushuwei/article/details/124155089
    更新时间:2022-10-20 11:56:50