简体   繁体   English

sql 查询具有 3 个具有多个值列的表

[英]sql query with 3 tables with multiple values column

I have 3 tables:我有 3 个表:

participants (id, name) groups (id, name) participant_groups (participant_id, group_id)参与者 (id, name) groups (id, name) participant_groups (participant_id, group_id)

I need to show a table with all the participants and a last column with the participant's groups, which can be several.我需要显示一张包含所有参与者的表格和最后一列参与者的组,这可以是多个。

I have the following select that returns all the participants but if it has more than one group I have several records of the same participant.我有以下 select 返回所有参与者,但如果它有多个组,我有同一参与者的多个记录。

SELECT *
    FROM participants
      CROSS JOIN groups
      INNER JOIN participant_groups
        ON groups.id = participant_groups.id
        AND participants.id = participant_groups.id
    ORDER BY participants.name, participants.id
    

Thanks谢谢

Just add a GROUP BY and GROUP_CONCAT :只需添加一个GROUP BYGROUP_CONCAT

SELECT participants.id, participants.name, GROUP_CONCAT(groups.name) AS group_list
FROM participants
LEFT JOIN participant_groups ON participants.id = participant_groups.participant_id
INNER JOIN groups ON participant_groups.group_id = groups.id
GROUP BY participants.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM