1

特定の user_id 間の会話を見つけるのに問題があります。

SQL テーブル:

+-------------------+
| conversation_user |
+-------------------+
| conversation_id   |
| user_id           |
+-------------------+

私はもう試した

SELECT `conversation_id` FROM `conversation_user` WHERE `user_id` IN (X, Y) HAVING COUNT(*) = N

しかし、正しく動作しません。正しい conversation_id を選択する方法はありますか? 会話は、1 人以上のユーザー間で行うことができます。

編集:

+-----------------+---------+
| conversation_id | user_id |
+-----------------+---------+
|               1 |       1 | 
|               1 |       2 | 
+-----------------+---------+
|               2 |       1 | 
|               2 |       3 | 
+-----------------+---------+
|               3 |       1 | 
+-----------------+---------+
|               4 |       1 | 
|               4 |       2 | 
|               4 |       3 | 
+-----------------+---------+

ユーザー 1 と 2 の間の会話を取得したいとしましょう。結果は、1 と 4 または 4 ではなく、1 でなければなりません。

4

3 に答える 3

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`
    )

SQLFiddle デモ

于 2012-10-16T14:57:21.033 に答える
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;
于 2012-10-16T15:48:50.190 に答える
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
于 2012-10-16T14:59:19.903 に答える