我有三张桌子:
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
,但结果很奇怪
我是否需要进行嵌套查询?
有什么想法吗?
答案 0 :(得分:25)
它并不是特别困难。
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
当用户根据评论在User_Sports中没有条目时,更新 LEFT JOIN
答案 1 :(得分:3)
我认为这只是一个简单的连接和聚合:
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