Many To Many Table Join With Pivot

前端 未结 2 1840
挽巷
挽巷 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: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.

提交回复
热议问题