我有一个产品表,想要选择所有 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/