views:

57

answers:

3

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 |          |
+-------+-------+----------|
+2  A: 

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

Alex Brasetvik
That doesn't guarantee the order of the `entity_id` for the output to match the expected result.
OMG Ponies
Where did he state that requirement?
Alex Brasetvik
+3  A: 

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.

OMG Ponies
No - backticks are for table and column names. He's using them correctly.
mozillalives
OMG Ponies
Ah, I understand what you were trying to say now. From your brief explanation I thought you misunderstood the use of backticks.
mozillalives
Awesome, this is working perfectly!
Aron Rotteveel
+2  A: 

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

mozillalives
That doesn't guarantee the order of the `entity_id` for the output to match the expected result.
OMG Ponies
That is correct, but he didn't ask for it. I could assume that that is what he wants, but he might not actually care what order in which case, it's unnecessary. Better to give him just what he needs (easier to understand) than a lot of options (which can make it harder to understand).
mozillalives