MySQL - 选择俱乐部名称并在一个查询中列出所有成员?

时间:2015-04-26 08:47:38

标签: mysql

  1. 我有一个"俱乐部"表和"成员"表
  2. 我想查询返回俱乐部名称(clubs.name)和每个成员的昵称(members.nickname)
  3. 我可以使用内部联接来获取它们,

    SELECT clubs.name AS `Club Name`, members.nickname AS `Member Handle`
    FROM clubs
    INNER JOIN members ON clubs.club_id = members.club_id
    

    但是显示了每个member.nickname的club.name字段。

    | Club Name   | Member Handle |
    -------------------------------   
    | Club Yellow | Jim-Bob       |
    | Club Yellow | Clem          | 
    | Club Yellow | Mustache Pete |
    | Club Green  | Ladyhawke     |
    | Club Green  | Rosie         |
    

    是否可以接收这样的结果?

    | Club Name   | Member Handle |
    -------------------------------   
    | Club Yellow | Jim-Bob       |
    |             | Clem          | 
    |             | Mustache Pete |
    | Club Green  | Ladyhawke     |
    |             | Rosie         |
    

    由于

1 个答案:

答案 0 :(得分:1)

没有在mysql中你无法生成这样的结果,你需要使用应用程序级别来完成它。但是,您可以格式化数据,即将所有member-handle格式化为逗号分隔值

SELECT 
clubs.name AS `Club Name`,
group_concat(members.nickname) AS `Member Handle`
FROM clubs
INNER JOIN members ON clubs.club_id = members.club_id 
group by clubs.name