mysql查询 - 2个外键

时间:2011-03-31 17:55:25

标签: mysql

我有这两个表

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

其中from_airportto_airport是外键。

我可以在airportidfrom_airportairportidto_airport上加入表格,我可以获得to_airport的名称或{{1}的名称但我想在一个查询中或以最低成本选择from_airportto_airport个名称。

有可能吗?如何??

这是我的问题:

from_airport

1 个答案:

答案 0 :(得分: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