我有三张这样的表
耦合
+----------+-------------+---------------+-----------------+
|couple_id | clubname | agegroup | group |
+----------+-------------+---------------+-----------------+
| 36 | club_1 | adults | C |
| 37 | club_2 | youth | A |
+----------+-------------+---------------+-----------------+
用户:
+----------+-------------+---------------+
|couple_id | firstname | lastname |
+----------+-------------+---------------+
| 36 | andy | hort |
| 36 | katrin | wilson |
| 37 | hans | gertes |
| 37 | julia | menz |
+----------+-------------+---------------+
培训地点:
+----------+-------------+
|couple_id | location |
+----------+-------------+
| 36 | Paris |
| 37 | Berlin |
| 37 | Paris |
+----------+-------------+
结果表应如下所示:
+---------+------------------------+--------+-----+----------------+
|couple_id| couple |agegroup|group|location |
+---------+------------------------+--------+-----+----------------+
| 36 |andy hort, katrin wilson| adults | C | Paris |
| 37 |hans gertes, julia menz | youth | A | Paris, Berlin |
+---------+------------------------+--------+-----+----------------+
是否有一个优雅的查询可以在一个查询中加入这些信息?
答案 0 :(得分:1)
您应该group_concat
使用distinct
:
select c.couple_id,
group_concat(distinct concat(u.firstname, " ", u.lastname)) couple,
c.agegroup,
c.groupd,
group_concat(distinct l.location) location
from couple c
join users u on c.couple_id = u.couple_id
join locations l on c.couple_id = l.couple_id
group by c.couple_id
如果couple
表中的记录可能不在users
或locations
表中,那么您可能需要使用outer join
。
@ spencer7593非常重要 - 您可以将聚合移动到子查询,以包含distinct
删除的潜在重复项:
select c.couple_id,
u.couple,
c.agegroup,
c.groupd,
l.location
from couple c
join (
select couple_id,
group_concat(concat(firstname, " ", lastname)) couple
from users
group by couple_id
) u on c.couple_id = u.couple_id
join (
select couple_id,
group_concat(location) location
from locations
group by couple_id
) l on c.couple_id = l.couple_id