MySQL 没有 ORDER BY 时按顺序 GROUP BY

MySQL GROUP BY order when no ORDER BY

在 MySQL 中,如果使用 GROUP BYORDER BY 未指定 ,结果集的顺序是什么?

我继承了带有如下查询的代码:

SELECT col1, COUNT(col1)
FROM table
GROUP BY col1

(其实SELECT语句可以比这复杂很多,涉及到JOIN等,但还是先从基本原理说起吧。)注意这里没有ORDER BY.

例如,在 SQL 服务器 BOL 中,我被告知:

The GROUP BY clause does not order the result set. Use the ORDER BY clause to order the result set.

我一直无法找到关于 MySQL GROUP BY 是否承诺单独从 GROUP BY 进行特定排序的声明?如果可以提供 MySQL 参考来支持任何最受欢迎的答案。

来自manual

If you use GROUP BY, output rows are sorted according to the GROUP BY columns as if you had an ORDER BY for the same columns. To avoid the overhead of sorting that GROUP BY produces, add ORDER BY NULL:

SELECT a, COUNT(b) FROM test_table GROUP BY a ORDER BY NULL;

Relying on implicit GROUP BY sorting (that is, sorting in the absence of ASC or DESC designators) is deprecated. To produce a given sort order, use explicit ASC or DESC designators for GROUP BY columns or provide an ORDER BY clause.