JOIN 和 GROUP_CONCAT 与三个表
我有三张桌子:
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
) 联系起来.
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
我尝试过 JOIN
和 GROUP_CONCAT
,但结果很奇怪.
我需要进行嵌套查询吗?
有什么想法吗?
I have tried with JOIN
and GROUP_CONCAT
but I get weird results.
Do I need to do a nested query?
Any ideas?
推荐答案
并不是特别困难.
- 使用 JOIN 子句连接三个表.
- 在您感兴趣的领域使用 Group_concat.
- 不要忘记未连接的字段上的 GROUP BY 子句,否则会发生奇怪的事情
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
演示
更新 LEFT JOIN 用于当用户根据评论在 User_Sports 中没有条目时
Update LEFT JOIN for when the user doesn't have entries in User_Sports as per comments
相关文章