如何在 MySQL 的同一列上使用两次 Left Join?
我有两张桌子,一张用于机场,一张用于航线。
机场看起来有点像这样
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'
,你可能知道也可能不知道,但行不通。 我该怎么做呢?
I have two tables, one for airports and one for routes.
Airports looks a little like this
Airports
-------------------------------------
id | code | name |
-------------------------------------
01 | LGW | London Gatwick |
-------------------------------------
02 | LHR | London Gatwick |
and so on....
and another for routes like this
Routes
---------------------------
id | ORIGIN | DESTINATION |
---------------------------
01 | LGW | VCE |
---------------------------
02 | TSF | LHR |
and so on...
I need to Select routes from the table, but I also want to get the airport names as well. The confusing bit is that I need to query the airport code twice. I'm trying something like this
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'
Which you may or may not know, doesn't work. How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用别名:
Use aliases:
只需给表指定两个不同的别名即可。 类似的东西(未经测试);
Just give the table two different aliases. Something like (untested);
您需要使用别名添加 AIRPORTS 表两次......
You need to add the AIRPORTS table twice using aliases....
在表名上添加别名:
Put an alias on the table names: