MySQL GROUP_CONCAT()对所有行进行分组

时间:2015-12-16 19:31:21

标签: mysql sql

我有以下查询:

select card.id as id, photo.image as photo
from card
left outer join card_image as photo on (photo.card=card.id)

返回

+----+-------+
| id | photo |
+----+-------+
|  1 |     2 |
|  1 |     3 |
|  1 |     4 |
|  2 |     5 |
|  2 |     6 |
+----+-------+

如果我将photo.image as photo更改为group_concat(photo.image) as photos,我会得到以下结果

+----+---------------+
| id | photo         |
+----+---------------+
|  1 |     2,3,4,5,6 |
+----+---------------+

但我的期望是

+----+-----------+
| id | photo     |
+----+-----------+
|  1 |     2,3,4 |
|  2 |     5,6   |
+----+-----------+

即。我想通过id

为每张卡片获取一组照片

2 个答案:

答案 0 :(得分:5)

GROUP_CONCAT()是一个聚合函数,如MAX()。它为每个组生成一行。组由GROUP BY子句定义,如果没有这样的子句 - 在您的情况下 - 所有行都属于同一组。您显然希望按card.id分组:

select
  card.id as id,
  group_concat(photo.image) as photos
from
  card
  left outer join card_image as photo
    on (photo.card = card.id)
group by card.id

另请注意,对于聚合查询,标准SQL允许仅选择组的分组列和功能。在您的原始示例中,没有分组列,因此您依赖MySQL扩展来完全选择card.id。另一方面,我在上面提到的代码在这方面是标准的(但group_concat()仍然是MySQL主义。)

答案 1 :(得分:2)

您应该将GROUP BY与您的查询一起使用:

select card.id as id, group_concat(photo.image) as photos
from card
left outer join card_image as photo on (photo.card=card.id)
GROUP BY id