2013-05-08 2 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과 같다 : 사용,321 0이면 idContactPayed[By/To] 열만 필수입니다 (NOT NULL). 이 열에서 null을 허용하는 경우 LEFT OUTER JOIN을 사용해야합니다. 제 생각에는 두 컬럼 모두 필수적이어야합니다.

참고 2 : 스타일의 문제 : old style joins (ANSI 86/89) : FROM table1 a, table2 b WHERE <join condition>을 피하십시오.

+0

감사합니다. Bogdan. –

관련 문제