组合一个表中的3个表的信息(MySQL)

时间:2016-03-08 23:24:18

标签: mysql jointable

我有三张这样的表

耦合

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

是否有一个优雅的查询可以在一个查询中加入这些信息?

1 个答案:

答案 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表中的记录可能不在userslocations表中,那么您可能需要使用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