0

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 |          |
+-------+-------+----------|
4

3 回答 3

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 关键字使用反引号。

于 2009-12-23T17:18:29.313 回答
2

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

于 2009-12-23T17:00:28.933 回答
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 ',' 因为这是默认设置,但至少您现在知道如何更改它 :)

于 2009-12-23T17:18:50.943 回答