在一个查询中聚合分组结果集中的所有单个列:是否可能?

时间:2009-12-23 16:57:14

标签: sql mysql string aggregate-functions

目前我有以下MySQL查询:

SELECT 
    COUNT(*) AS `count`, 
    `v`.`value` 
FROM `client_entity_int` AS `v` 
INNER JOIN `client_entity` AS `e` 
ON e.id = v.entity_id 
WHERE (v.attribute_id = '1') AND (e.deleted = 0) 
GROUP BY `v`.`value`

返回以下内容:

+-------+-------+
| count | value |
+-------+-------+
|     9 |     0 |
|    11 |     1 |
+-------+-------+

我想要返回的是上面的内容,包括显示上述查询中找到的所有entity_id的逗号分隔聚合的列。

这可能在同一个查询中,如果可以,怎么做?例如:

+-------+------------------+
| count | value | entities |
+-------+-------+----------|
|     9 |     0 |  1,2,3,4 |
|    11 |     1 |          |
+-------+-------+----------|

3 个答案:

答案 0 :(得分:3)

使用:

  SELECT COUNT(*) 'count', 
         v.value,
         GROUP_CONCAT(DISTINCT v.entity_id ORDER BY v.entityid ASC SEPARATOR ',') 'entities'
    FROM client_entity_int AS v 
    JOIN client_entity AS e ON e.id = v.entity_id 
   WHERE v.attribute_id = '1'
     AND e.deleted = 0
GROUP BY v.value

参考:GROUP_CONCAT

您只需要为MySQL关键字使用反引号。

答案 1 :(得分:2)

group_concat(entity_id SEPARATOR ',') AS entities添加到混音中。

答案 2 :(得分:2)

像Alex建议的那样使用group_concat。所以你的查询看起来像是

SELECT 
    COUNT(*) AS `count`, 
    `v`.`value`,
    GROUP_CONCAT(entity_id SEPARATOR ',') as entities
FROM `client_entity_int` AS `v` 
INNER JOIN `client_entity` AS `e` 
ON e.id = v.entity_id 
WHERE (v.attribute_id = '1') AND (e.deleted = 0) 
GROUP BY `v`.`value`

你实际上可以不使用SEPARATOR','因为这是默认设置,但至少你现在知道如何改变它:)