mysql - GROUP_CONCAT() 不能单独使用?

标签 mysql aggregate-functions

我有一个产品表,想要选择所有 ID 作为逗号分隔的字符串。当我运行以下查询时:

SELECT GROUP_CONCAT(p.id SEPARATOR ',') FROM products p GROUP BY 1

我收到错误:

Can't group on 'GROUP_CONCAT(p.id SEPARATOR ',')'

但是,如果我将查询更改为:

SELECT id, GROUP_CONCAT(p.id SEPARATOR ',') FROM products p GROUP BY 1

然后它为每个产品返回一行,其中包含两列,每列中都有一个匹配的产品 ID。这不是我想要的,但我显示此查询是为了证明选择一个额外的列会导致错误消失。

为什么GROUP_CONCAT()不能自己使用?

最佳答案

如果您想将所有 找到的行分组为一个,那么您根本不需要GROUP BY 子句。

来自docs :

If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.

你应该能够做到:

SELECT GROUP_CONCAT(p.id SEPARATOR ',') FROM products p

请注意,SEPARATOR ','默认值,您可以只使用:

SELECT GROUP_CONCAT(p.id) FROM products p

根据docs对于 SELECT 语句,您可以将 position 传递给 GROUP BY,它将按该列分组。

Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names, column aliases, or column positions. Column positions are integers and begin with 1 [...] Use of column positions is deprecated because the syntax has been removed from the SQL standard.

因此,GROUP BY 1 被解释为 GROUP BY GROUP_CONCAT(p.id SEPARATOR ','),这是没有意义的。

关于mysql - GROUP_CONCAT() 不能单独使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34184284/

相关文章:

mysql - 统计MYSQL表中某个点之前的记录

scala - Scala 聚合函数的示例

mysql - 我如何在mySQL中复制一堆记录

sql - 兼容各种关系型数据库的boolean数据类型

php - 加入两个表以匹配整数以获得用户名

mysql - 如何避免错误 "aggregate functions are not allowed in WHERE"

php - 尝试使用计数和分组依据构建 mysql 查询

python - python 处理时锁定 innoDB MySQL 中的记录

php - 在 mySql 中获取最大值的时间

MySQL sum, count with group by 和 joins