将 3 table 秒的信息合并为一个 table (MySQL)

Combine information from 3 tables in one table (MySQL)

我有三个这样的table

情侣

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

结果 table 应如下所示:

+---------+------------------------+--------+-----+----------------+
|couple_id| couple                 |agegroup|group|location        |
+---------+------------------------+--------+-----+----------------+
| 36      |andy hort, katrin wilson| adults | C   | Paris          |
| 37      |hans gertes, julia menz | youth  | A   | Paris, Berlin  |
+---------+------------------------+--------+-----+----------------+

是否有一种优雅的查询方式可以将这些信息合并到一个查询中?

你应该使用 group_concatdistinct:

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 table 中的记录可能不存在于 userslocations table 中,那么您可能需要使用取而代之的是 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