JOIN and GROUP_CONCAT with three tables

后端 未结 2 1753
感情败类
感情败类 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

    0 讨论(0)
  • 2020-12-14 22:57

    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
    
    0 讨论(0)
提交回复
热议问题