0

我的架构如下:

  • 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我的意思是“arrival_airport_id”的名称departure_airport_idarrival_airport但是在飞行记录上获取两个机场的名称的正确方法是什么?

4

3 回答 3

2

从航班加入到 airports 表中两次,如下所示:

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
于 2012-04-04T10:31:43.107 回答
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

如果您使用不同的别名,则多次加入表没有问题。

于 2012-04-04T10:34:09.607 回答
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
于 2012-04-04T10:34:25.847 回答