Question

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 |          |
+-------+-------+----------|
Was it helpful?

Solution

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.

OTHER TIPS

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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top