如何仅选择以特定 topic_id(“5000”)开始并包含多个 topic_id 的 session ?伪代码中的 WHERE 子句中的代码。
request_id session_id topic_id
1 1 3000
2 1 5000
3 2 5000
4 2 3000
5 2 6000
6 3 5000
SELECT
min(request_id),
session_id,
group_concat(topic_id order by request_id asc SEPARATOR ' ,')
FROM requests
WHERE (first(topic_id) = '5000' AND count(topic_id) > 1)
group by session_id
order by request_id asc
result:
request_id session_id topic_id
3 2 5000, 3000, 6000
我知道这应该适用于子查询,但我不知道如何操作。谢谢!!
最佳答案
您可以使用 HAVING
子句将查询更改为如下所示
SELECT
request_id,
session_id,
group_concat(topic_id order by request_id)
FROM sessions
GROUP BY session_id
HAVING MIN(topic_id) = '5000'
AND COUNT(DISTINCT topic_id) > 1
ORDER BY request_id;
关于MySQL group_concat WHERE 字段中的第一项具有特定 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34635004/