代码之家  ›  专栏  ›  技术社区  ›  atkayla

找到双方都参与的聊天记录

  •  0
  • atkayla  · 技术社区  · 7 年前
    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都在的聊天室id。如果没有,则返回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没有共同的聊天id,因此它不应该返回任何内容。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Avi    7 年前

    我想你可能没有补充存在条件的地方。

     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
    
        2
  •  3
  •   Thorsten Kettner    7 年前

    最简单的方法是聚合:

    select chat_id
    from chat_person
    group by chat_id
    having bool_or(person_id = 2) and bool_or(person_id = 20);
    
        3
  •  0
  •   Zaynul Abadin Tuhin    7 年前

    如果您需要所有其他字段,可以尝试下面的方法

    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

        4
  •  0
  •   Himanshu    7 年前

    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