MySQL: 如何过滤掉不包含特定值的组?

MySQL: How to filter out groups that don't contain a specific value?

我想过滤掉属于不包含 site_id 2 的会话的所有 request_id。因此,如果用户没有访问站点 2,该会话与我无关。

request_id   session_id   site_id
1            1            1
2            1            2
3            1            3
4            2            1
5            2            3
6            2            3

结果:

request_id   session_id   site_id
1            1            1
2            1            2
3            1            3

我知道我可以想到类似的东西(没有检查是否有效):

SELECT
session_id,
GROUP_CONCAT(site_id order by request_id asc SEPARATOR ', ') as site_ids
FROM requests
GROUP BY session_id
HAVING site_id LIKE ('% 2, %' OR '2, %')
ORDER BY session_id asc;

但我还需要相关的 session_ids 不聚合在一个单元格中。那么是否可以避免生成输出的GROUP BY session_id

你们有更好更高效的解决方案吗?

我认为您可能需要使用子select来达到预期的结果。

SELECT
request_id, session_id, site_id
FROM requests
WHERE session_id in (
  select distinct session_id FROM requests where site_id=2)
ORDER BY session_id asc;

或加入

SELECT
A.request_id, A.session_id, A.site_id
FROM requests A
RIGHT JOIN requests B ON
   A.session_id = B.session_id AND B.site_id=2
GROUP BY A.session_id
ORDER BY A.session_id asc;

我只想做一个子查询来检查 session_id 是否有对 site_id = 2 的请求。

SELECT
session_id,
GROUP_CONCAT(site_id order by request_id asc SEPARATOR ', ') as site_ids
FROM requests r
WHERE EXISTS(SELECT NULL FROM requests WHERE session_id = r.session_id AND site_id = 2)
GROUP BY session_id
ORDER BY session_id asc;