目前我有以下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 | |
+-------+-------+----------|
答案 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','因为这是默认设置,但至少你现在知道如何改变它:)