Many To Many Table Join With Pivot

前端 未结 2 1834
挽巷
挽巷 2021-01-04 11:51

I currently have two tables similar to users and programs that are linked through a many-to-many relationships by way of a link table.

相关标签:
2条回答
  • 2021-01-04 12:33
    SELECT users.name, group_concat(programs.name) from linker
    INNER JOIN users on linker.user_id = users.id
    INNER JOIN programs on linker.program_id = programs.id
    GROUP BY users.id;
    
    0 讨论(0)
  • 2021-01-04 12:50

    You need to specify a DISTINCT, i.e.

    select users.name, group_concat( DISTINCT programs.name)
    

    See the MySQL docs here.

    Try changing your query to:

    SELECT users.name, group_concat(programs.name) 
    from users
    LEFT JOIN linker on linker.user_id = users.id
    LEFT JOIN programs on linker.program_id = programs.id
    GROUP BY users.id
    

    This will give you a null for any user with no programs associated with them. To filter them out, just add a WHERE programs.id IS NOT NULL.

    0 讨论(0)
提交回复
热议问题