查找双方都参与的聊天

时间:2019-02-27 06:01:10

标签: sql postgresql

chat_person
---
id chat_id person_id
1   1      20
2   1      19
3   2      19
4   2      3
5   3      19
6   3      2

我正在尝试找到同时位于p1 = 20和p2 = 2的chat_id。如果不存在,则不返回任何内容。

SELECT DISTINCT "t1".chat_id
FROM "chat_person" t1
WHERE 
    EXISTS (
        SELECT 1 FROM "chat_person" t2
        WHERE "t2".person_id = 20
    )
    AND "t1".person_id = 2

此查询错误地返回了chat_id: 3。没有person_id = 20和person_id = 2的通用chat_id,因此它不应返回任何内容。

4 个答案:

答案 0 :(得分:3)

我认为您可能错过了添加条件存在的地方。

 SELECT DISTINCT "t1".chat_id
FROM "chat_person" t1
WHERE 
    EXISTS (
        SELECT 1 FROM "chat_person" t2
        WHERE "t2".person_id = 20 and t2.ChatID = "t1".chat_id  
    )
    AND "t1".person_id = 2

答案 1 :(得分:3)

最简单的方法是聚合:

select chat_id
from chat_person
group by chat_id
having bool_or(person_id = 2) and bool_or(person_id = 20);

答案 2 :(得分:0)

这是您想要的吗?

SELECT chat_id, count(distinct 
person_id) from table 
group by chat_id having 
  count(case when person_id in (2,20)
 then person_id end)=2

答案 3 :(得分:0)

如果您需要其他所有字段,可以尝试以下操作

select t1.* from chat_person t1
 where exists ( select 1 from chat_person t2 where t2.chat_id=t1.chat_id
                                and person_id in (2,20)
                               having count(distinct person_id)=2)

或者,如果您只需要chat_id

,则可以简单地执行以下操作
   select chat_id from cte t2 where 
   person_id in (2,20)
   group by chat_id
   having count(distinct person_id)=2

demo