1

我正在开发消息系统。

基本上我有 2 个表,对话表只保留 id,关系表保留对话 id 和对话中的用户 id。

我的关系表;

|----------------|--------|
| CONVERSATIONID | USERID |
|----------------|--------|
|       1        |   1    |
|       1        |   2    |
|       2        |   2    |
|       2        |   3    |
|       3        |   1    |
|       3        |   2    |
|       3        |   3    |
|       3        |   4    |
|       4        |   3    |
|       4        |   1    |
|       4        |   2    |
|----------------|--------|

当用户想要发送新消息时,我正在检查用户之间是否有对话。例如,用户 (id 1) 选择 userid 2 来发送消息,但他们已经有了对话,需要将消息添加到此对话中。

所以,我的问题是我无法在一个查询中获取现有的对话 ID。

我可以通过此查询获取属于用户的对话 ID;

SELECT DISTINCT CONVERSATIONID FROM RELATIONS
WHERE CONVERSATIONID IN 
(
    SELECT DISTINCT CONVERSATIONID FROM RELATIONS WHERE USERID IN ( 1,2 )
)

result : 1,2,3,4

如果我运行这个查询;

SELECT DISTINCT CONVERSATIONID FROM RELATIONS
WHERE CONVERSATIONID IN 
(
    SELECT DISTINCT CONVERSATIONID FROM RELATIONS WHERE USERID IN ( 1,2 )
)
AND USERID NOT IN ( 1,2 )

result : 2,3,4

但我需要“id : 1”,即这些用户的对话。

如何通过一次查询获得此 ID?

谢谢

4

1 回答 1

3

这个问题叫做Relational Division

假设UserID每个 都是唯一的CONVERSATIONID

SELECT  CONVERSATIONID
FROM    conversationTable a
WHERE   UserID IN (1, 2) AND   -- <<== list of UserID you want to find
        EXISTS
        (
            SELECT  1
            FROM    conversationTable b
            WHERE   a.CONVERSATIONID = b.CONVERSATIONID
            GROUP   BY CONVERSATIONID
            HAVING  COUNT(*) = 2 -- <<== number of userID on the list
        )
GROUP   BY CONVERSATIONID
HAVING  COUNT(*) = 2 -- <<== number of userID on the list
于 2013-05-10T08:45:05.500 回答