4

我有两张桌子,一张用于机场,一张用于路线。

机场看起来有点像这样

Airports
-------------------------------------
id | code | name                    |
-------------------------------------
01 | LGW  | London Gatwick          |
-------------------------------------
02 | LHR  | London Gatwick          |

等等....

另一个用于这样的路线

Routes
---------------------------
id | ORIGIN | DESTINATION |
---------------------------
01 | LGW    | VCE         |
---------------------------
02 | TSF    | LHR         |

等等...

我需要从表中选择路线,但我也想获得机场名称。令人困惑的是我需要两次查询机场代码。我正在尝试这样的事情

SELECT routes.*, airports.name as origin_name FROM routes
LEFT JOIN airports ON airports.IATA = routes.origin
LEFT JOIN airports ON airports.IATA = routes.destination
WHERE origin = 'LHR' AND destination = 'VCE' OR origin = 'VCE'

您可能知道也可能不知道,这不起作用。我该怎么做呢?

4

4 回答 4

18

使用别名:

SELECT
    routes.*,
    a1.name AS origin_name,
    a2.name AS destination_name
FROM routes r
LEFT JOIN airports a1 ON a1.IATA = r.origin
LEFT JOIN airports a2 ON a1.IATA = r.destination
WHERE
    r.origin = 'LHR' AND r.destination = 'VCE' OR r.origin = 'VCE'
于 2009-06-08T20:23:10.913 回答
4

只需给表两个不同的别名。类似的东西(未经测试);

SELECT routes.*, o.name as origin, d.name as destination FROM routes
LEFT JOIN airports o ON o.IATA = routes.origin
LEFT JOIN airports d ON d.IATA = routes.destination
WHERE origin = 'LHR' AND destination = 'VCE' OR origin = 'VCE'
于 2009-06-08T20:22:57.170 回答
3

您需要使用别名添加两次 AIRPORTS 表......

SELECT ORIGIN_AIRPORT.NAME,
       DESTINATION_AIRPORT.NAME
FROM   AIRPORTS ORIGIN_AIRPORT,
       AIRPORTS DESTINATION_AIRPORT,
       ROUTES
WHERE  ROUTES.ORIGIN = ORIGIN_AIRPORT.CODE
AND    ROUTES.DESTINATION = DESTINATION_AIRPORT.CODE;
于 2009-06-08T20:23:38.073 回答
2

在表名上加上别名:

SELECT routes.*, a1.name as origin_name FROM routes
LEFT JOIN airports AS a1 ON a1.IATA = routes.origin
LEFT JOIN airports AS a2 ON a2.IATA = routes.destination
WHERE origin = 'LHR' AND destination = 'VCE' OR origin = 'VCE'
于 2009-06-08T20:24:00.913 回答