我有这两张桌子

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

其中from_airportto_airport是外键。
我可以在airportidfrom_airportairportidto_airport上连接表,我可以得到to_airport的名称或from_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

最佳答案

别名你的桌子,当你做接缝:

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

关于mysql - mysql查询-2个外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5504166/

10-11 05:39