-2

我坚持创建 SQL 查询。我有以下两个表:

member
(
 memberid    int,
 membername  varchar(50)
)

message
(
 messageid   int, 
 message     varchar(100), 
 sender      int, 
 receiver    int
)

sender并且receiver是带有 tablemember和 column的外键memberid。我想显示带有nameid的消息列表senderreceiver

我怎样才能在这里建立正确的连接?

4

2 回答 2

3

你可以尝试类似的东西

SELECT  *
FROM    message m INNER JOIN
        member snd ON   m.sender = snd.memberid INNER JOIN
        member rcv ON   m.receiver = rcv.memberid
于 2012-07-15T11:05:07.103 回答
1

我会LEFT OUTER JOIN在这种情况下使用,因为您的message.sendermessage.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;

http://sqlfiddle.com/#!3/ac80e/2/0

于 2012-07-15T11:16:25.657 回答