我正在处理可能有多个参与者的会话话题。
我有一个映射如下所示的SQL表:
Table: conversation_participants
conversation_id participant_name
--------------- ----------------
1 Al
1 Bob
1 Carl
2 Al
2 Carl
3 Bob
4 Al
4 Bob
5 Carl
给定一组participant_name
,我希望能够找到包含那些参与者的单个conversation_id
(如果存在)。有人可以帮我确定实现此目的所需的SQL吗?
我已经经历了各种不同的方法,我认为这有效:
-- Given:
-- participant_names: a list of participant names, like ('Al', 'Bob')
-- n: size of participant_names
SELECT conversation_id
FROM conversation_participants
WHERE participant_name IN participant_names
AND conversation_id IN (
SELECT conversation_id
FROM conversation_participants
GROUP BY conversation_id HAVING count(*) = n
)
GROUP BY conversation_id HAVING count(*) = n;
子查询首先生成具有conversation_id
个参与者的n
个。然后,WHERE
子句会过滤以包含对话的每一行,该对话包含与n
中某个参与者对应的participant_names
个参与者。最后,最后一个GROUP BY
会导致我们从conversation_id
查询中排除任何未生成n
行的WHERE
个。{/ p>
然而,上述查询似乎非常复杂和冗余(对我来说)应该相当简单。有更好的方法吗?
谢谢!
答案 0 :(得分:1)
这是删除where
条件并使用conditional aggregation
的一个选项:
SELECT conversation_id
FROM conversation_participants
GROUP BY conversation_id
HAVING sum(case when participant_name IN participant_names then 1 else n + 1 end) = n
答案 1 :(得分:0)
SELECT conversation_id
FROM conversation_participants
WHERE participant_name IN participant_names
GROUP BY conversation_id
HAVING Count(*) = n