mySQL,PHP,组合查询以确定我属于线程中有多少未读消息


mySQL, PHP, Combine queries to determine how many unread messages in threads I belong

我有一个这样的 sql 表msg_to_user

mtu_id | sender_id | receiver_id | mtu_thread | mtu_read

我使用两个查询来确定

  1. 我参与了多少次对话(我的ID是8907)
SELECT * FROM msg_to_user
WHERE 8907 IN (sender_id, receiver_id)
GROUP BY mtu_thread
ORDER BY mtu_id DESC
  1. 然后对于每个循环,在 php 中,我查询这些对话中存在多少未由我发送的未读 (mtu_read = 0) 消息
SELECT *
FROM msg_to_user
WHERE mtu_read = 0
AND sender_id != " . $mpage->IdNum . "
AND mtu_thread = [the thread[$i] unique id resulted form previous query]

我基本上想知道是否有办法将这些查询组合在一起而不是两个查询

您可以使用子查询来计算未读消息的数量。下面的示例使用速记table as并使用 select 子查询来获取线程中未读消息的数量,而不是由用户发送的。您可以根据表结构优化此查询。

SELECT 
    m.*, 
    (SELECT 
        COUNT(*) 
        FROM msg_to_user mj
        WHERE mj.mtu_read = 0
        AND mj.sender_id != ".$mpage->IdNum."
        AND mj.mtu_thread = m.mtu_thread
    ) as mCount
FROM msg_to_user m
WHERE ".$mpage->IdNum." IN (m.sender_id, m.receiver_id)
GROUP BY m.mtu_thread
ORDER BY m.mtu_id DESC