MySQL连接在同一个字段上

时间:2012-01-07 10:08:23

标签: mysql join

我有两张桌子:

  1. 消息 - 具有以下结构

    ID
    SENDER_ID
    receiver_id
    message_text

  2. 用户 - 具有以下结构

    ID
    昵称

  3. 我需要加入这两个表,所以我得到这样的结果:

    message_id, sender_nickname, receiver_nickname, message_text
    
    始终设置

    sender_id。问题是我还需要receiver_id为0的邮件,因此receiver_id表格中找不到user

    有人可以帮助我吗?

5 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

看起来像这样:

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

如果右侧表没有匹配值,则LEFT [OUTER] JOIN保证不会排除左侧表。

答案 2 :(得分: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

当没有数据时,保持receiver_id列为NULL而不是INT值为0。

答案 3 :(得分:0)

将messages表连接到receiver_id上的用户表时,应使用左外连接。

答案 4 :(得分:0)

您可以在其中使用外部联接

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>