2013-08-31 113 views
0

我不確定如果我正在以正確的方式進行操作,所以我會很感激現實檢查。兩張桌子;用戶和Feed。MySQL加入並創建一個新表(?)

+--------+-----------+----------+----------+ 
| userid | firstname | lastname | username | 
+--------+-----------+----------+----------+ 
|  63 | Chris  | Smith | csmith | 
|  65 | Roger  | Smith | rsmith | 
|  66 | Diane  | Smith | dsmith | 
+--------+-----------+----------+----------+ 

+-----------+--------+-----------+----------------+ 
| messageid | userid | contactid | subject  | 
+-----------+--------+-----------+----------------+ 
|   4 | 67  | 63  | Test message 1 | 
|   5 | 67  | 63  | Test message 2 | 
|   6 | 63  | 67  | Test message 3 | 
|   7 | 63  | 67  | Test message 4 | 
|   8 | 65  | 66  | Test message 5 | 
|   9 | 65  | 66  | Test message 6 | 
|  10 | 66  | 65  | Test message 7 | 
|  11 | 66  | 65  | Test message 8 | 
+-----------+--------+-----------+----------------+ 

當我產生用戶的頁面上的消息,我就必須提出,他們是在用戶ID(發起者),或使用ContactID(收件人)的消息。用戶的用戶名將被使用。但是,我需要顯示用戶的用戶名,而不是他們的用戶ID。所以,這似乎是一個加入聲明,我可以組成一個聯合,將幾乎所有這些信息彙集在一起​​。

select a.userid, b.username, a.contactid, 
     a.subject, a.message, a.timestamp 
from feed as a, 
     users as b 
where a.userid=b.userid 

結果:

+--------+----------+-----------+----------------+-------------------------------------+ 
| userid | username | contactid | subject  | message        | 
+--------+----------+-----------+----------------+-------------------------------------+ 
| 67  | Kimomaru | 63  | Test message 1 | This is a test, hello, hello, hello | 
| 67  | Kimomaru | 63  | Test message 2 | This is a test, hello, hello, hello | 
| 63  | csmith | 67  | Test message 3 | This is a test, hello, hello, hello | 
+--------+----------+-----------+----------------+-------------------------------------+ 

不過,我想使用ContactID,將顯示收件人的用戶名,這將來自於用戶的表username列後添加一列。我怎樣才能做到這一點?

回答

1
select a.userid, b.username, a.contactid, 
     c.username, a.subject, a.message, a.timestamp 
from feed as a, users as b , users as c 
where a.userid=b.userid and a.contactid=c.userid 
+0

哦,哇,我沒有想到再次引用同一張表作爲c。非常感謝你,我真的很感激。 – Kimomaru

相關問題