Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

mysql - JOIN and GROUP_CONCAT with three tables

I have three tables:

users:        sports:           user_sports:

id | name     id | name         id_user | id_sport | pref
---+--------  ---+------------  --------+----------+------
 1 | Peter     1 | Tennis             1 |        1 |    0
 2 | Alice     2 | Football           1 |        2 |    1
 3 | Bob       3 | Basketball         2 |        3 |    0
                                      3 |        1 |    2
                                      3 |        3 |    1
                                      3 |        2 |    0

The table user_sports links users and sports with an order of preference (pref).

I need to make a query that returns this:

id | name  | sport_ids | sport_names
---+-------+-----------+----------------------------
 1 | Peter | 1,2       | Tennis,Football
 2 | Alice | 3         | Basketball
 3 | Bob   | 2,3,1     | Football,Basketball,Tennis

I have tried with JOIN and GROUP_CONCAT but I get weird results.
Do I need to do a nested query?
Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...