我有两个名为conversations
和users
的表,它们与包含conversation_user
和user_id
列的数据透视表conversation_id
绑定。
| conversation_id | user_id |
|-----------------|---------|
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
我想向数据库发送一些用户ID并检索它们在一起的对话。
例如:
当我发送1
和2
时,我必须收到conversation_id 1
,当我发送1
,2
和3
时我必须收到conversation_id 2
。
我怎么写这样的查询?
答案 0 :(得分:3)
您可以使用GROUP BY
和HAVING
:
SELECT conversation_id
FROM tab -- subquery/temp table/whatever
GROUP BY conversation_id
HAVING SUM(user_id = 1) > 0
AND SUM(user_id = 2) > 0
AND SUM(user_id = 3) > 0
AND SUM(user_id NOT IN (1,2,3)) = 0
的 SqlFiddleDemo
强>
对于1和2:
SELECT conversation_id
FROM tab
GROUP BY conversation_id
HAVING SUM(user_id = 1) > 0
AND SUM(user_id = 2) > 0
AND SUM(user_id NOT IN (1,2)) = 0
答案 1 :(得分:0)
Group_concat可用于根据您的要求检索结果。您可以相应地更改having子句条件:试试这个让我知道
SELECT conversion_id
FROM (
SELECT
conversion_id,
group_concat(user_id, ',')
FROM conversions
HAVING group_concat(user_id, ',') = '1,2,3'
GROUP BY conversion_id
)