我的架构如下:
airports
表包含机场名称。它的主键是整数id
。flights
表格包含航班数据。它有两个外键departure_airport_id
和arrival_airport_id
我想在航班上获取出发和到达机场的名称。现在我的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
和{{1}}的名称我是指'arrival_airport_id'的名称,但在航班记录上获取两个机场名称的正确方法是什么?
答案 0 :(得分: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
答案 1 :(得分: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
如果使用不同的别名,可以多次连接到表格。
答案 2 :(得分: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