2

I have two tables:

  1. messages - with following structure

    id
    sender_id
    receiver_id
    message_text

  2. users - with following structure

    id
    nickname

I need to join these two tables so I get result like this:

message_id, sender_nickname, receiver_nickname, message_text

sender_id is always set. The problem is I also need messages where receiver_id is 0 so receiver_id can't be found in user table.

Could someone help me?

5 Answers 5

2
select 
m.id,
u1.nickname as sender,
u2.nickname as receiver,
m.message_text
from messages as m
left join users as u1 on u1.id = m.sender_id
left join users as u2 on u2.id = m.receiver_id
0
1

Could look like this:

SELECT m.id AS message_id
      ,u1.nickname AS sender_nickname
      ,u2.nickname AS receiver_nickname
      ,m.message_text
FROM   messages m
LEFT   JOIN users u1 ON u1.id = m.sender_id
LEFT   JOIN users u2 ON u2.id = m.receiver_id

A LEFT [OUTER] JOIN guarantees that the left hand table will not be excluded if the right hand table has no matching value.

0
1
SELECT ...
FROM messages
INNER JOIN users AS senders ON senders.id = messages.sender_id
LEFT JOIN users AS receivers ON receivers.id = messages.receiver_id

And keep the receiver_id column NULL instead of an INT value of 0, when there's no data.

0

You should use a left outer join when joining the messages table to the user table on the receiver_id.

0

You can use outerjoin in it

select 
m.id as message_id, us.nickname as sender_nickname, ur.nickname as receiver_nickname, m.message_text as message_text
from messages m join users us on us.id = m.sender_id
left outer join users ur.id = m.receiver_id
where m.id = <your message id>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.