CONCAT周围的GROUP_CONCAT发出错误 - 组功能的使用无效

时间:2013-02-02 12:06:01

标签: mysql concat group-concat

我正在尝试GROUP_CONCAT以下查询返回的结果:

SELECT
      CONCAT(p.product_name, " (", SUM(bp.quantity), ")") AS products
FROM product p
INNER JOIN booking_products bp ON p.product_id = bp.product_id
GROUP BY p.product_id

此查询返回以下内容:

------------
| products |
------------
Shampoo (3)
Advil (1)
Dry Shampoo (4)
Cepacol (5)

当我尝试运行下面的查询时,我收到一个错误:“#1111 - 无效使用组功能”。这有什么问题?

SELECT
    GROUP_CONCAT(
        CONCAT(p.product_name, " (", SUM(bp.quantity), ")") 
        SEPARATOR ", "
    ) AS products
FROM product p
INNER JOIN booking_products bp ON p.product_id = bp.product_i
GROUP BY p.product_id

肯定会回来:

Shampoo (3), Advil (1), Dry Shampoo (4), Cepacol (5)

感谢您的帮助。

1 个答案:

答案 0 :(得分:6)

SELECT GROUP_CONCAT(products) FROM
(
    SELECT CONCAT(p.product_name, " (", SUM(bp.quantity), ")") AS products
    FROM product p
    INNER JOIN booking_products bp ON p.product_id = bp.product_id
    GROUP BY p.product_id
) x

GROUP_CONCAT无效,因为您已经使用了SUM,这是一个GROUP函数。