0

「コスト」と「連絡先」の 2 つのテーブルがあります。すべての売り手と買い手の名前は「連絡先」テーブルにあります。次のクエリでは、各アイテムの売り手と買い手の 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
4

1 に答える 1

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の場合にのみ使用します ( )。これらの列が null を許可する場合は、を使用する必要があります。私の意見では、両方の列が必須であるべきです。idContactPayed[By/To]NOT NULLLEFT OUTER JOIN

注 2: スタイルの問題:古いスタイルの結合は避けてください (ANSI 86/89) : FROM table1 a, table2 b WHERE <join condition>.

于 2013-05-08T11:13:21.357 に答える