SQL中使用聚合函数时,关联的列会被选中吗?

When using an aggregate function in SQL, will the associated columns be selected?

我有以下查询

SELECT
  day,
  category_id,
  name,
  qval
  MIN(CONCAT(category_id, qval))
FROM facts
WHERE
  day = CURDATE()
GROUP BY
  category_id

被选中的 name 是否总是与识别的 MIN 记录关联的 name

绝对不是。没有理由期望会出现这种情况。这是您的查询:

SELECT day, category_id, name, qval
       MIN(CONCAT(category_id, qval))
FROM facts
WHERE day = CURDATE()
GROUP BY category_id;

虽然没有这样标识,但此语法是 MySQL。您正在使用 MySQL 扩展,因为 select 中的列不是聚合函数的参数,也不在 group by 中。这些值来自 任意 行。这里有一些关于扩展使用的相关documentation

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.

我相信此问题已在 MySQL 5.7 中得到解决,因为 5.7 检测到函数依赖性。