如何加入具有特定条件的表

时间:2017-06-19 09:33:44

标签: mysql sql

我想从这样的表中选择数据(表名为conversations_users):

Table content sample

我希望能够检索仅包含两个用户的会话ID。例如,如果我搜索特定于用户1和3的对话,则对话号码6应该是唯一的结果,因为对话5还包括用户2。

我试图执行像

这样的请求
SELECT * FROM conversations_users AS table1 JOIN 
              conversations_users AS table2 ON
              table1.conversation_ID = table2.conversationID
        WHERE table1.userID = 3 AND
              table2.userID = 1 

但是它返回了对话5和6.如何解决这个问题?

提前谢谢你,

皮尔

5 个答案:

答案 0 :(得分:2)

添加ON子句:

SELECT * FROM conversations_users AS table1 JOIN 
              conversations_users AS table2 
                ON table1.conversation_ID = table2.conversation_ID
        WHERE table1.userID = 3 AND
              table2.userID = 1

<强>更新: 要获得仅涉及1和3的覆盖,您可以使用having子句:

SELECT table1.conversation_ID FROM conversations_users AS table1 JOIN 
              conversations_users AS table2 
                ON table1.conversation_ID = table2.conversation_ID
        WHERE table1.userID = 3 AND
              table2.userID = 1
        Group by table1.conversation_ID 
        having Count(*) = 2

答案 1 :(得分:0)

您需要的查询如下:

SELECT conversation_ID, GROUP_CONCAT(DISTINCT userID ORDER BY userID) as users
FROM conversations_users
GROUP BY conversation_ID
HAVING users = '1,3'

GROUP BY子句对具有相同conversation_ID的行进行分组,并从每个组生成一条新记录,其中包含conversation_IDuserID的不同值,升序,与逗号(,)连接。

HAVING子句仅保留'1,3'子句计算的users列中GROUP BY的记录。

查询会生成您需要的输出,但效率不高,因为它会读取整个表。通过首先选择用户13的对话,然后仅将上述内容应用于他们,可以提高效率。

看起来像这样:

SELECT conversation_ID, GROUP_CONCAT(DISTINCT userID ORDER BY userID) as users
FROM (
    SELECT *
    FROM conversations_users
    WHERE userID in (1, 3)
) conversations
GROUP BY conversation_ID
HAVING users = '1,3'

为了比上一个查询更快地工作,conversations_users必须在userID列上有一个索引。

答案 2 :(得分:0)

如果您想限制那些涉及n个用户的会话。我认为下面的通用查询应该工作。根据要求替换'n'。

select * 
from  conversations_users
where conversation_id IN (select conversation_id
                      from conversations_users
                      group by conversation_id
                      having count(userid) = 2)

谢谢, 阿穆布巴克

答案 3 :(得分:0)

内部选择与除1或3之外的其他用户

一起获取所有conversationID

外部选择(带有不同的)收集所有不在此子集中的对话

SELECT DISTINCT conversationID
  FROM conversations_users t1
 WHERE conversationID NOT IN ( SELECT conversationID
                                 FROM conversations_users
                                WHERE userID NOT in (1, 3)
                             )

答案 4 :(得分:0)

在这种情况下,你可以使用where where where condition。

SELECT #, userid ,conversation_ID FROM user AS table1 JOIN 
              conversations_users AS table2 
                ON user_ID = conversation_ID
        WHERE table1.userID = 3 AND
              table2.userID = 1
        Group by conversation_ID 

您可以通过where子句而不是group by

来应用合适的条件