2012-04-04 7 views
0

내 스키마가 동일한 유형의 두 개의 데이터베이스 컬럼의 관련 이름을 가져옵니다 :다음과 같이

  • airports 표는 공항 이름을 보유하고 있습니다. 기본 키는 정수, id입니다.
  • flights 테이블에는 항공편 데이터가 저장됩니다. 그것은 두 개의 외래 키, departure_airport_idarrival_airport_id

나는 비행기에 departure- 및 도착 공항 모두의 이름을 얻기 위해 노력하고 있습니다. 지금 내 SQL은 다음과 같다 :

SELECT name AS departure_airport, name AS arrival_airport FROM flights, airports WHERE departure_airport_id = airports.id OR arrival_airport_id = airports.id 

나는 데이터베이스 departure_airport에 의해 내가 departure_airport_id의 이름을 의미하는 것을 알 수 없기 때문에이 모호 방법을 볼 수 arrival_airport에 의해 내가 'arrival_airport_id'의 이름을 의미한다, 그러나 비행 기록에있는 두 공항의 이름을 얻는 올바른 방법은 무엇입니까?

답변

2

은과 같이, 공항 테이블에 항공편에서 두 번 가입 : 다른 별칭을 사용하는 경우

SELECT dep.name AS departure_airport, arr.name AS arrival_airport 
FROM flights f 
    JOIN airports dep ON f.departure_airport_id = dep.id 
    JOIN airports arr ON f.arrival_airport_id = arr.id 
+0

우수합니다. 감사! – Laurens

1
SELECT departure_airport.name AS departure_airport, 
      arrival_airport.name AS arrival_airport 
     FROM flights 
INNER JOIN airports departure_airport 
     ON departure_airport.id = flights.departure_airport_id 
INNER JOIN airports arrival_airport 
     ON arrival_airport.id = flights.arrival_airport_id 

가 한 번 이상 테이블에 합류 아무 문제가 없습니다.

1
SELECT depart.name AS departure_airport, arr.name AS arrival_airport 
FROM flights, airports arr,airports depart 
WHERE departure_airport_id = depart.id and 
arrival_airport_id = arr.id