找到两个人都参与的聊天

问题描述 投票:0回答:4
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

我试图找到chat_id,其中p1 = 20和p2 = 2都在。如果没有,则返回none。

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,因此不应返回任何内容。

sql postgresql
4个回答
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

3
投票

最简单的方法是聚合:

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

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


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
© www.soinside.com 2019 - 2024. All rights reserved.