I have a user table as below
table.users
{id:1, name:'USER 1'}
{id:2, name:'USER 2'}
{id:3, name:'USER 3'}
{id:4, name:'USER 4'}
The USER 1 sends message to all users with a chat window id is inserted in table.messages
table.messages
{id:1,chat_id:1, from_user:1: message:'Hi'}
{id:2,chat_id:1, from_user:1: message:'How are you'}
{id:3,chat_id:1, from_user:1: message:'This is broadcasted'}
table.last_read
{id:1, last_read_message_id:3, user_id:2, chat_id:1}
{id:2, last_read_message_id:3, user_id:3, chat_id:1}
I am using the below query to fetch the unread message by the user , as the table.last_read inserting only when alteast one read ,USER 4 will not have record in table.last_read, the below returns last_read_message_id null in the left join and returns 0 records
SELECT COUNT(*) FROM messages m
LEFT JOIN (
SELECT last_read_message_id
FROM last_read
WHERE user_id=4
) lr ON m.chat_id=lr.chat_id
WHERE m.chat_id=1 AND m.id>last_read_message_id