根据多行结果选择一条记录

时间:2013-07-24 17:16:36

标签: mysql database-design

我有两张桌子:

|  conversations  |      |    conversation_participants   |
-------------------      ----------------------------------
| id | project_id |      | id | conversation_id | user_id |
-------------------      ----------------------------------
  1  | 1                   1  | 1               | 1
  2  | 1                   2  | 1               | 2
                           3  | 2               | 1
                           4  | 2               | 3 

我需要选择两个用户对特定项目ID具有共同的会话ID

所以在这个例子中:

  • user_id 1和user_id 2对project_id 1的共同对话ID为: 1
  • user_id 1和user_id 3对project_id 1的共同对话ID为: 2

我需要一个查询,我可以在其中提供user_id a,user_id b和project_id,并获得会话ID。

我尝试过类似的事情:

SELECT
c.id
FROM conversations c
JOIN conversation_participants p ON p.conversation_id = c.id
WHERE (p.user_id = ? AND c.project_id = ?)
OR (p.user_id = ? AND c.project_id = ?)

但当然这会返回多行并且可能是错误的,因为在某些情况下它会返回具有不同会话ID的记录...

帮助表示感谢!谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个

   SELECT
    c.id
   FROM conversations c
   JOIN conversation_participants p ON p.conversation_id = c.id
   JOIN conversation_participants p2 ON p2.conversation_id = p.conversation_id
   WHERE  c.project_id = ?
   AND p.user_id = ? and p2.user_id = ?

你可以给:

p.user_id = 1   --as user1
p2.user_id = 2  --as user2
c.project_id = 1 

DEMO HERE