我想过滤掉属于不包含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
?
您有更好,更有效的解决方案吗?
答案 0 :(得分:1)
我认为您可能需要使用子选择来实现所需的结果。
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;
答案 1 :(得分:1)
我只是做一个子查询来检查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;