我在找到给定user_ids之间的对话时遇到问题。
SQL表:
+-------------------+
| conversation_user |
+-------------------+
| conversation_id |
| user_id |
+-------------------+
我试过
SELECT `conversation_id` FROM `conversation_user` WHERE `user_id` IN (X, Y) HAVING COUNT(*) = N
但它无法正常工作。知道如何选择正确的conversation_id吗?对话可以在一个或多个用户之间进行。
编辑:
+-----------------+---------+
| conversation_id | user_id |
+-----------------+---------+
| 1 | 1 |
| 1 | 2 |
+-----------------+---------+
| 2 | 1 |
| 2 | 3 |
+-----------------+---------+
| 3 | 1 |
+-----------------+---------+
| 4 | 1 |
| 4 | 2 |
| 4 | 3 |
+-----------------+---------+
假设我希望得到用户1和2之间的对话。结果必须是1,而不是1和4或4。
答案 0 :(得分:2)
我认为你缺少GROUP BY
条款
<击> 撞击>
<击>SELECT `conversation_id`
FROM `conversation_user`
WHERE `user_id` IN (X, Y)
GROUP BY conversation_id
HAVING COUNT(DISTINCT user_id) = N
击> <击> 撞击>
或
SELECT `conversation_id`
FROM `conversation_user` a
WHERE `user_id` IN (X, Y)
GROUP BY conversation_id
HAVING COUNT(DISTINCT user_id) =
(
SELECT COUNT(DISTINCT userid)
FROM `conversation_user` b
WHERE b.`conversation_id` = a.`conversation_id`
GROUP BY b.`conversation_id`
)
答案 1 :(得分:1)
已更新!我解决了此查询的问题。
SELECT cu.`conversation_id`
FROM `conversation_user` cu
INNER JOIN (
SELECT `conversation_id`
FROM `conversation_user`
WHERE `user_id` IN (X, Y)
GROUP BY `conversation_id` HAVING COUNT(*) = Z
) cu2 ON cu.conversation_id=cu2.conversation_id
GROUP BY `conversation_id`
HAVING COUNT(*) = Z;
答案 2 :(得分:0)
SELECT `conversation_id`,count(*) Number_of_conversations FROM `conversation_user`
WHERE `user_id` IN (X, Y) and
`user_id` not in(select `user_id` from `conversation_user` where `user_id` not in(X, Y))
GROUP BY `conversation_id`
HAVING COUNT(*) = 2