我有三张桌子:
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
该表user_sports
链接users
并按sports
优先顺序 ( pref
)。
我需要做一个返回这个的查询:
id | name | sport_ids | sport_names
---+-------+-----------+----------------------------
1 | Peter | 1,2 | Tennis,Football
2 | Alice | 3 | Basketball
3 | Bob | 2,3,1 | Football,Basketball,Tennis
我试过了JOIN
,GROUP_CONCAT
但我得到了奇怪的结果。
我需要做一个嵌套查询吗?
有任何想法吗?