检查群组对话中是否已存在线程

时间:2015-07-15 10:44:05

标签: mysql

我是一个用户发送消息的平台。可以进行群组对话。

我的thread_members表:

id | user_id | thread_id 
------------------------- 
 1 |    1    |     1   
------------------------- 
 2 |    2    |     1  
------------------------- 
 3 |    1    |     2  
------------------------- 
 4 |    2    |     2  
------------------------- 
 5 |    3    |     2  
------------------------- 
 6 |    1    |     3  
------------------------- 
 7 |    3    |     3  
------------------------- 
 8 |    4    |     3  

当我发送消息时,我想检查该线程是否已经存在。

让我们说:user_id' 1'向user_id' 2'

发送消息

结果应该是thread_id' 1'

应该是单个查询

修改

感谢大家,但我想我得到了答案: 我现在没有遇到任何问题...

在PHP中:

$senderId = $_POST['sender']; // integer
$receiverIds = $_POST['receivers']; // array

$query = "SELECT thread_members.*, COUNT(*) 
          FROM thread_members 
          JOIN (   
            SELECT *, COUNT(*)   
            FROM (     
              SELECT *     
              FROM thread_members     
              WHERE user_id = " . $senderId . " "; 

              foreach ($receiverIds as $receiverId) 
              {
                $query .= " OR user_id = " . $receiverId . " ";  
              }

              $query .= " ) AS thread_members 
            GROUP BY thread_id 
            HAVING COUNT(*) = " . (count($receiverIds) + 1) . "
            ORDER BY COUNT(*) 
          ) AS thread_members_copy ON thread_members.thread_id = thread_members_copy.thread_id 
          GROUP BY thread_members.thread_id 
          HAVING COUNT(*) = " . (count($receiverIds) + 1) . "
          ORDER BY COUNT(*) ";

(count($receiverIds) + 1)都是接收者+发件人

1 个答案:

答案 0 :(得分:0)

您可以进行自我加入,然后检查包含两个用户ID值的记录:

SELECT t1.thread_id FROM
thread_members t1 INNER JOIN thread_members t2
ON t1.thread_id = t2.thread_id
WHERE t1.user_id = 1 AND t2.user_id = 2