我与用户之间存在多对多关系,并且正在获得用户使用子查询播放的所有运动名称的串联字符串。我的结构如下:
user
===============
| id | name |
---------------
| 1 | Hugo |
| 2 | Paco |
| 3 | Luis |
---------------
sport
=================
| id | name |
-----------------
| 1 | tennis |
| 2 | football |
| 3 | handball |
-----------------
user_sport
======================
| user_id | sport_id |
----------------------
| 1 | 3 |
| 1 | 1 |
| 2 | 1 |
----------------------
如何从列表中进行任何运动的用户过滤结果,例如让所有打网球或手球的用户获得结果。
我正在尝试以下查询:
SELECT u.id, u.name,
COALESCE (
(SELECT GROUP_CONCAT(s.name SEPARATOR ', ')
FROM sport AS s
LEFT JOIN user_sport AS us ON us.sport_id = s.id
WHERE us.user_id = u.id),'') AS sports
FROM user u
WHERE us.sport_id IN (1,3)
GROUP BY u.id
ORDER BY g.name
但是它不起作用,因为where子句不知道user_sport
表。因此,我必须在子查询之外创建一个新的JOIN吗?
答案 0 :(得分:2)
您必须两次加入user_sport
。一次将其过滤为仅包含列表中的运动项目,另一次则获得所选用户参与的所有运动项目。
SELECT u.id, u.name, GROUP_CONCAT(s.name SEPARATOR ', ') AS sports
FROM user AS u
JOIN user_sport AS us_filtered ON u.id = us_filtered.user_id
JOIN user_sport AS us_all ON u.id = us_all.user_id # all
JOIN sport AS s ON s.id = us_all.sport_id
WHERE us_filtered.sport_id IN (1, 3)
GROUP BY u.id
ORDER BY u.name