简体   繁体   English

在SQL中使用聚合函数时,是否会选择关联的列?

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

I have the following query 我有以下查询

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

Will the name that gets selected always be the name associated with the MIN record that is identified? 选择的name将始终是与所标识的MIN记录相关联的name吗?

Absolutely not. 绝对不。 There is no reason to expect this to be the case. 没有理由期望情况会如此。 This is your query: 这是您的查询:

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

Although not identified as such, this syntax is MySQL. 尽管没有这样标识,但该语法是MySQL。 You are using a MySQL extension because you have columns in the select that are not arguments to aggregation functions and are not in the group by . 您使用的是MySQL扩展,因为select中有一些列不是聚合函数的参数,也不在group by These values come from arbitrary rows. 这些值来自任意行。 Here is some relevant documentation concerning the use of the extension: 以下是有关扩展名使用的一些相关文档

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. MySQL扩展了GROUP BY的使用,以便选择列表可以引用未在GROUP BY子句中命名的非聚合列。 This means that the preceding query is legal in MySQL. 这意味着前面的查询在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. 但是,这主要在每个未聚合列中未在GROUP BY中命名的所有值对于每个组都相同时才有用。 The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. 服务器可以从每个组中自由选择任何值,因此,除非它们相同,否则选择的值是不确定的。

I believe this problem is fixed in MySQL 5.7, because 5.7 detects functional dependency. 我相信此问题已在MySQL 5.7中解决,因为5.7检测到功能依赖性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM