2011-03-08 22 views
2

如何使用左連接構造mySQL查詢以解決此問題?如何使用left-join爲這種類型的問題編寫mySQL?

Feed Table 
-id 
-lastpost_id (The id of the user from USER TABLE who last posted) 
-firstpost_id (The id of the user from USER TABLE who first posted) 

User Table 
-id 
-name 

我希望得到一個表像

Result 
-id 
-lastpost_id 
-lastpost_name 
-firstpost_id 
-firstpost_name 

回答

5
select *, a.name as lastpost_name, b.name as firstpost_name from Feed f 
     left join user a on f.lastpost_id=a.id 
     left join user b on f.firstpost_id=b.id 

訣竅是左連接,然後別名表爲a或b。通過這種方式,您可以對同一個表進行多次連接。

+1

也許可以提及您可以調用別名。爲了清楚起見,建議使用簡短的_descriptive_名稱。我會叫他們u1和u2,或者u_lp和u_fp。 – nitro2k01 2011-03-08 23:24:55

+0

非常好的一點。我之所以沒有這樣做的唯一原因是因爲它在本例中是建立在列名稱中的 - 即「firstpost_name」和「lastpost_name」 – Jason 2011-03-09 00:17:40

相關問題