JOIN and GROUP_CONCAT with three tables

后端 未结 2 1762
感情败类
感情败类 2020-12-14 22:17

I have three tables:

users:        sports:           user_sports:

id | name     id | name         id_user | id_sport | pref
---+--------  ---+------------           


        
2条回答
  •  独厮守ぢ
    2020-12-14 22:34

    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

提交回复
热议问题