我有以下查询:
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为每张卡片获取一组照片
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-ism).