2012-07-15 37 views
-1

我一直在創建一個SQL查詢。 我有以下兩個表:無法創建適當的sql

member 
(
memberid int, 
membername varchar(50) 
) 

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

senderreceiver外鍵與表member和列memberid。我想要顯示nameidsenderreceiver的消息列表。

有人可以幫助我,因爲我無法在這裏建立適當的連接嗎?

回答

3

你可以嘗試像

SELECT * 
FROM message m INNER JOIN 
     member snd ON m.sender = snd.memberid INNER JOIN 
     member rcv ON m.receiver = rcv.memberid 
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