如何根据一张桌子中的两个机场代码选择两个机场名称?

时间:2012-12-10 20:10:25

标签: sql postgresql

我有这个架构:

CREATE TABLE Airport (
  airportIATA CHAR(3) NOT NULL,
  name VARCHAR(45) NOT NULL, 
  PRIMARY KEY (airportIATA) 
  );

CREATE TABLE Flight (
  flightNumber VARCHAR(6) NOT NULL,
  timeOfDeparture TIME NOT NULL,
  departureAirport_IATA CHAR(3) NOT NULL REFERENCES Airport(airportIATA),
  stopOverAirport_IATA CHAR(3) REFERENCES Airport(airportIATA),
  arrivalAirport_IATA CHAR(3) NOT NULL REFERENCES Airport(airportIATA),
  PRIMARY KEY (flightNumber, departureAirport_IATA, arrivalAirport_IATA)
  );

有这些记录:

INSERT INTO Airport VALUES ('HEL','Helsinki/Vantaa Airport');
INSERT INTO Airport VALUES ('STO','Stockholm Airport');
INSERT INTO Airport VALUES ('TAL', 'Lennart Meri Tallinn Airport');

INSERT INTO Flight VALUES ('AY101', '13:30', 'HEL', NULL, 'STO');
INSERT INTO Flight VALUES ('AA202', '16:15', 'STO', 'TAL', 'HEL');

到目前为止,我有这些疑问:

SELECT flightNumber, timeOfDeparture, departureAirport_IATA, arrivalAirport_IATA
FROM Flight
WHERE stopOverAirport_IATA IS NULL;



SELECT flightNumber, timeOfDeparture, name AS 'Arrival Airport'
FROM Flight, Airport
WHERE Flight.stopOverAirport_IATA IS NULL AND Flight.arrivalAirport_IATA = Airport.airportIATA;

我的问题是,如何更改后一个查询,使其包含到达和放置的名称。出发机场(我们在第一次查询中获得IATA代码)?

1 个答案:

答案 0 :(得分:3)

尝试这样的事情:

SELECT
  flightNumber, 
  timeOfDeparture, 
  DA.name AS 'Departure Airport',
  AA.name AS 'Arrival Airport'
FROM
  Flight As F
  INNER JOIN Airport As DA
  ON F.departureAirport_IATA = DA.airportIATA
  INNER JOIN Airport As AA
  ON F.arrivalAirport_IATA = AA.airportIATA
WHERE 
  F.stopOverAirport_IATA IS NULL
;