MySql 中子查询的过滤结果

Filtering results from a subquery in MySql

我有一个多对多的用户运动关系,我正在使用子查询获得用户玩的所有运动名称的串联字符串。我的结构如下:

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 table。那么,我必须在子查询之外创建一个新的 JOIN 吗?

您必须加入 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