A
A
Alexey Konovalov2019-05-29 13:39:32
MySQL
Alexey Konovalov, 2019-05-29 13:39:32

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

Please pay attention to AND mr.`user_id` = 111 . This condition is simply necessary for me, because I need to know whether this particular user has read this message.
But the MySql documentation says to avoid conditions in the JOIN construct.
Can you tell me what is the best way to deal with this situation?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
ThunderCat, 2019-05-29
@Alk90

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

E
egor_nullptr, 2019-05-29
@egor_nullptr

If the request fulfills in a time acceptable to you, then do not change anything.

V
Valery, 2019-05-29
@Desay

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

D
d-stream, 2019-05-29
@d-stream

You can put the condition in where - modern optimizers in both cases will build the same optimal plan

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question