2011-03-31 96 views
2

我有這兩個表MySQL查詢 - 2個外鍵

airports: airportid, airportname 
flights: flightid, from_airport, to_airport 

其中from_airportto_airport是外鍵。

我可以連接的表或者在airportidfrom_airportairportidto_airport,要麼我得到的to_airportfrom_airport名字名字,但我想無論是在一個查詢或以最低的成本來選擇這兩個to_airportfrom_airport名。

有沒有可能?怎麼樣??

這裏是我的查詢:做的時候

SELECT 
flight.idflight, 
flight.idairline, 
flight.from_airport, 
flight.to_airport, 
flight.number, 
airports.name AS origin 
FROM 
flight 
Inner Join airports ON flight.from_airport = airports.idairports 

回答

2

別名你的表的聯接:

SELECT 
    flight.idflight, 
    flight.idairline, 
    flight.from_airport, 
    flight.to_airport, 
    flight.number, 
    airport_from.name AS origin 
    airport_to.name AS destination 
FROM flight 
    INNER JOIN airports airport_from ON flight.from_airport = airport_from.idairports 
    INNER JOIN airports airport_to ON flight.to_airport = airport_to.idairports