Reputation: 1691
I am building a messaging system for a CMS and can not find a way to get the number of unread messages in a message chain.
I need a way to find out if the main message or any of it's reply messages are unread.
I have a table called "messages" that has the fields: id, active[1,0], subject, message, datetime, user_from, user_to, reply, viewed, removed
When a message is read I store that users id comma-delimited in the viewed field: ,3,4,12,
Then to find out if it's viewed I look for the sender's id like this:
m.viewed LIKE '%,$user_id,%'
I just figure out how to get that logic into this SQL select so that I can see if a parent message should be marked as unread. The following SQL works great and grabs all the messages and the number of replies and orders them by datetime.
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
Any help would be greatly appreciated... I can't wrap my head around it!
Upvotes: 0
Views: 2382
Reputation: 115660
You should check this article: Managing Hierarchical Data in MySQL
--EDIT--UPDATE
OK, you only have 1 level of replies so no need for the above.
Try this:
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
;
Upvotes: 1