SQL显示未读消息的数量...包括未读回复

时间:2011-03-23 07:47:24

标签: php mysql messaging

我正在为CMS构建消息传递系统,但无法找到获取消息链中未读消息数量的方法。

我需要一种方法来确定主要消息或其任何回复消息是否未读。

我有一个名为“messages”的表,其中包含以下字段: id,active [1,0],subject,message,datetime,user_from,user_to,reply,viewing,removed

当读取消息时,我将用户id以逗号分隔的方式存储在已查看的字段中: ,3,4,12,

然后要查明是否已查看,我会查找发件人的ID:

m.viewed LIKE '%,$user_id,%'

我只是弄清楚如何将这个逻辑放入这个SQL select中,以便我可以看到父消息是否应该被标记为未读。以下SQL工作得很好,可以抓取所有消息和回复数量,并按日期时间对它们进行排序。

SELECT m.*, COUNT(*) AS num_replies, MAX(r.datetime) AS max_datetimeunread_replies
FROM directus_messages AS m
LEFT JOIN directus_messages as r
    ON m.id = r.reply
WHERE m.active = '1' 
AND m.removed NOT LIKE '%,$user_id,%' 
GROUP BY m.id
HAVING m.reply = '0' 
ORDER BY datetime DESC, max_datetime DESC

任何帮助都将不胜感激......我无法绕过它!

1 个答案:

答案 0 :(得分:1)

您应该查看这篇文章:Managing Hierarchical Data in MySQL

- 编辑 - UPDATE

好的,您只有1级回复,因此不需要上述内容。

试试这个:

SELECT m.*
     , COUNT(*) AS num_replies
     , MAX(r.datetime) AS max_datetime
     , (m.viewed LIKE '%,$user_id,%') 
         AS message_viewed    --shows True or False
     , SUM(r.viewed NOT LIKE '%,$user_id,%')
         AS unread_replies    --shows number of unread replies
FROM directus_messages AS m
  LEFT JOIN directus_messages as r
    ON m.id = r.reply
WHERE m.active = '1' 
  AND m.removed NOT LIKE '%,$user_id,%' 
GROUP BY m.id
HAVING m.reply = '0' 
ORDER BY m.datetime DESC
       , max_datetime DESC
;