我想从这样的表中选择数据(表名为conversations_users
):
我希望能够检索仅包含两个用户的会话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.如何解决这个问题?
提前谢谢你,
皮尔
答案 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_ID
和userID
的不同值,升序,与逗号(,
)连接。
HAVING
子句仅保留'1,3'
子句计算的users
列中GROUP BY
的记录。
查询会生成您需要的输出,但效率不高,因为它会读取整个表。通过首先选择用户1
和3
的对话,然后仅将上述内容应用于他们,可以提高效率。
看起来像这样:
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
来应用合适的条件