生成查询

时间:2013-05-10 08:40:07

标签: mysql sql

我正在开发消息系统。

基本上我有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    |
|----------------|--------|

当用户想要发送新消息时,我正在检查用户之间是否有对话。例如,用户(标识1)选择用户标识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?

由于

1 个答案:

答案 0 :(得分: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