2011-04-30 42 views
0

如果有人能夠幫助我,請將此事表示感謝。我有兩個簡單的表,我想創建一個(不是那麼簡單)的查詢。我的一個表存儲用戶數據,另一個存儲用戶之間發送的消息。像這些:加入並與MySQL工會訂購

TABLE1 
userid, username 
0, Alice 
1, Bob 
2, Tom 
3, Jerry 

TABLE2 
messageid, senderid, recipientid, message 
0, 3, 2, "Hello Tom, how are you?" 
1, 2, 3, "Hello Jerry" 
2, 2, 0, "Happy Birthday Alice, Hugs, Tom" 
3, 3, 1, "Bob, what's up there?" 

我想創建任何給定用戶的聯繫人列表。我的意思是,這是一個有序的列表,其中包含從給定用戶獲取消息或向他/她發送消息的用戶名。因此,湯姆的聯繫人列表如下所示:

Alice 
Jerry 

而Bob的聯繫人列表將只包含Jerry。等等。

我想,也許我必須使用兩個選擇操作並將它們聯合起來。例如:

(select senderid from TABLE2 where recipientid=2) 
union 
(select recipientid from TABLE2 where senderid=2) 

我有三個問題。

如何在這裏使用JOIN來查看TABLE1中的名稱而不是TABLE2中的ID?

如何根據名稱對結果進行排序?

而且,是否有可能以任何其他方式解決這個問題?

謝謝。

回答

0

我還沒有測試過,但這個查詢應該給你湯姆的聯繫人列表。

SELECT DISTINCT t1.username 
    FROM table1 t1 JOIN (
     SELECT senderid AS userid, recipientid AS contactid FROM table2 
     UNION 
     SELECT recipientid as userid, senderid as contactid from table2 
    ) t2 on t1.userid = t2.contactid 
    WHERE t2.userid = 2 
    ORDER BY t1.username 
0
select userId, userName 
from 
    ((select senderid as userId from TABLE2 where recipientid=2) 
    union 
    (select recipientid as userId from TABLE2 where senderid=2) as innerView) 
join TABLE1 
where innerView.userid = TABLE1.userid 

我生疏,通常使用Oracle它具有標準的SQL,但這一想法的差異應該持有,即使我的語法是有點過。

0

我還沒有執行它,但我希望這適合您的要求。

SELECT T1.username AS sender, T2.Receiver AS Receiver 
FROM 
    table1 T1, 
    (SELECT table1.username AS receiver FROM table1,table2 
    WHERE table2.senderid = table1.userid AND table1.userid = t1.userid 
) AS T2 
WHERE T1.username = 'Tom';