[英]MySQL get multiple result from one table in one row
兩個表是“成本”和“聯系人”。 所有賣家和買家的名字都在“聯系人”表中。 使用以下查詢我檢索每個項目的賣方和買方的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
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:僅當idContactPayed[By/To]
列是必需的( NOT NULL
)時才使用INNER JOIN
。 如果這些列允許空值,那么您應該使用LEFT OUTER JOIN
。 在我看來,兩列都應該是強制性的。
注2:作為一種風格:請避免舊式連接(ANSI 86/89) : FROM table1 a, table2 b WHERE <join condition>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.