MySQL从一行中的一个表中获得多个结果

时间:2013-05-08 11:09:29

标签: mysql

这两个表是“成本”和“联系人”。所有卖家和买家的名字都在“联系人”表中。使用以下查询我检索每个项目的卖家和买家的ID,但我想从“联系人”表中获取他们的名字

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

1 个答案:

答案 0 :(得分: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>