Answer the question
In order to leave comments, you need to log in
How to perform a LEFT JOIN with a condition?
Hello. I have two tables:
messages - stores messages.
messages_read - stores data about whether the message was read by the user.
When I get a list of messages from the database and want to determine if the message has been read by the current user, I have to do a LEFT JOIN and the query comes out like this.
SELECT m.`id`, m.`message`, mr.`readed`
FROM `messages` m
LEFT JOIN `messages_read` mr ON mr.`message_id` = m.`id` AND mr.`user_id` = 111
WHERE m.`chat_id` = 12
Answer the question
In order to leave comments, you need to log in
If it were necessary to determine whether the user has read the message, it would make sense to do the selection exactly as you have, but specifying mr.`user_id` in the return fields, which would be either an id or null. If you have a LOT of people in the chat, then it would be more correct to do this:
SELECT m.`id`, m.`message`, mr.`message_id` status
FROM `messages` m
LEFT JOIN (
select `message_id`
from `messages_read`
where `user_id` = 111
) mr
ON mr.`message_id` = m.`id`
WHERE m.`chat_id` = 12
If the request fulfills in a time acceptable to you, then do not change anything.
SELECT m.`id`, m.`message`, case when mr.`message_id` is not null then 'Прочитано' else 'Не прочитано' end as iRead
FROM `messages` m
LEFT JOIN `messages_read` mr ON mr.`message_id` = m.`id`
WHERE m.`chat_id` = 12 and AND mr.`user_id` = 111
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question