JOIN and GROUP_CONCAT with three tables

こ雲淡風輕ζ 提交于 2019-11-28 21:37:54

Its not particularly difficult.

  1. Join the three tables using the JOIN clause.
  2. Use Group_concat on the fields you're interested in.
  3. Don't forget the GROUP BY clause on the fields you're not concatenating or weird things will happen


SELECT u.id, 
       u.Name, 
       Group_concat(us.id_sport order by pref) sport_ids, 
       Group_concat(s.name order by pref)      sport_names 
FROM   users u 
       LEFT JOIN User_Sports us 
               ON u.id = us.id_user 
       LEFT  JOIN sports s 
               ON US.id_sport = s.id 
GROUP  BY u.id, 
          u.Name 

DEMO

Update LEFT JOIN for when the user doesn't have entries in User_Sports as per comments

I think this is just a simple join and aggregation:

select u.id, u.name, group_concat(s.name order by pref separator ',')
from user_sports us join
     users u
     on us.id_user = u.id join
     sports s
     on us.id_sport = s.id
group by u.id, u.name
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!