2013-05-08 78 views
0

這兩個表是「成本」和「聯繫人」。所有賣家和買家的名字都在「聯繫人」表中。隨着下面的查詢我檢索賣方和買方對每個項目的ID,但我想從「聯繫人」表MySQL從一行中的一個表中獲得多個結果

SELECT 
costs.id as ID, 
costs.idContactPayedBy, 
costs.idContactPayedTo 

FROM costs 

WHERE 
costs.idbuilding=286 

得到他們的名字,但我想從聯繫人表中獲取賣家和買家的名字

SELECT 
costs.id as ID, 
contacts.lastname as seller, 
contacts.lastname as buyer 

FROM costs , contacts 

WHERE 
costs.idbuilding=286 
and costs.idContactPayedBy = contacts.id 
and costs.idContactPayedTo = contacts.id 

所以期望的結果是這樣的

ID Seller Buyer 
21 jackson Brown 
29 Bush  wilson 

回答

2
SELECT 
c.id as ID, 
cntby.lastname as seller, 
cntto.lastname as buyer 

FROM costs AS c 
INNER JOIN contacts AS cntby ON c.idContactPayedBy = cntby.id 
INNER JOIN contacts AS cntto ON c.idContactPayedTo = cntto.id 
WHERE c.idbuilding=286 

注1:使用INNER JOIN僅當idContactPayed[By/To]列爲必填項(NOT NULL)。如果這些列允許空值,那麼您應該使用LEFT OUTER JOIN。在我看來,這兩欄應該是強制性的。

注2:作爲款式:請避免old style joins (ANSI 86/89)FROM table1 a, table2 b WHERE <join condition>

+0

非常感謝Bogdan。 – 2013-05-08 12:49:37

相關問題