我坚持创建SQL查询。 我有以下两个表:
member
(
memberid int,
membername varchar(50)
)
message
(
messageid int,
message varchar(100),
sender int,
receiver int
)
sender
和receiver
是包含表格member
和列memberid
的外键。我想显示name
和id
sender
和receiver
的消息列表。
有人可以帮助我,因为我无法在这里建立适当的联接吗?
答案 0 :(得分:3)
您可以尝试类似
的内容SELECT *
FROM message m INNER JOIN
member snd ON m.sender = snd.memberid INNER JOIN
member rcv ON m.receiver = rcv.memberid
答案 1 :(得分:1)
我会在这种情况下使用LEFT OUTER JOIN
,因为您的message.sender
和message.receiver
允许NULL
值。如果这些列中的任何一列是NULL
:
select msg.messageid as messageid,
msg.message as message,
mem1.memberid as sender_id,
mem1.membername as sender_name,
mem2.memberid as receiver_id,
mem2.membername as receiver_name
from message as msg
left outer join member as mem1 on msg.sender = mem1.memberid
left outer join member as mem2 on msg.receiver = mem2.memberid;