开发者

Aggregrate all a single column in a grouped resultset in one query: is it possible?

At the moment I have the following MySQL query:

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`

Which returns the following:

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

What I would WANT it to return is the above, INCLUDING a column showing a comma-separated aggregate of all entity_id's found in the above query.

Is this possible in the same query, and if so, how? Example:

+-------+------------------+
| count | value | entities |
+-------+-------+----------|
|     9 |     0 |  1,2,3,4 |
|    11 |     1 |          |
+-------+--开发者_运维技巧-----+----------|


Use:

  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

Reference: GROUP_CONCAT

You only need to use backticks for MySQL keywords.


Add group_concat(entity_id SEPARATOR ',') AS entities to the mix.


Using group_concat like Alex suggested. So your query looks like

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`

you can actually leave off the SEPARATOR ',' because that's the default, but at least you know how to change it now :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜