如何在多列上进行INNER JOIN

我正在做一个家庭作业项目,我应该执行一个数据库查询,通过城市名称或机场代码查找航class,但flights表只包含机场代码,所以如果我想按城市search,我有joinairports表。

机场表有以下列: code, city
航class表有以下列: airline, flt_no, fairport, tairport, depart, arrive, fare
fairporttairport列是机场代码。
列出发和arrive的date是出发和到达。

我想出了一个查询,首先joinfairport列和fairport列的airports.code 。 为了让我能够匹配tairport我必须在第一次join之前对前一场比赛进行另一次join。

 SELECT airline, flt_no, fairport, tairport, depart, arrive, fare FROM (SELECT * FROM flights INNER JOIN airports ON flights.fairport = airports.code WHERE (airports.code = '?' OR airports.city='?')) AS matches INNER JOIN airports ON matches.tairport = airports.code WHERE (airports.code = '?' OR airports.city = '?') 

我的查询返回正确的结果,它将足够的作业的目的,但我想知道如果我可以JOIN多个列? 我将如何构造WHERE子句,以便匹配出发地和目的地城市/代码?

下面是我想要达到的“伪查询”,但我无法正确地获取语法,我不知道如何表示出发地和目的地的airports表:

 SELECT * FROM flights INNER JOIN airports ON flights.fairport = airports.code AND flights.tairport = airports.code WHERE (airports.code = 'departureCode' OR airports.city= 'departureCity') AND (airports.code = 'destinationCode' OR airports.city = 'destinationCity') 

更新

我还发现SQL Join语句的这种可视化表示对于如何构造SQL语句是非常有帮助的。

您可以通过为连接的表赋予一个别名来多次连接同一个表,如下例所示:

 SELECT airline, flt_no, fairport, tairport, depart, arrive, fare FROM flights INNER JOIN airports from_port ON (from_port.code = flights.fairport) INNER JOIN airports to_port ON (to_port.code = flights.tairport) WHERE from_port.code = '?' OR to_port.code = '?' OR airports.city='?' 

请注意, to_portfrom_portairports表的第一个和第二个副本的别名。

就像是….

 SELECT f.* ,a1.city as from ,a2.city as to FROM flights f INNER JOIN airports a1 ON f.fairport = a1. code INNER JOIN airports a2 ON f.tairport = a2. code 

如果mysql可以的话:

 SELECT flights.*, fromairports.city as fromCity, toairports.city as toCity FROM flights LEFT JOIN (airports as fromairports, airports as toairports) ON (fromairports.code=flights.fairport AND toairports.code=flights.tairport ) WHERE flights.fairport = '?' OR fromairports.city = '?' 

编辑:添加示例来过滤代码或城市的输出

你可以在on子句中使用吗?

例如,像这样的东西:

 SELECT airline, flt_no, fairport, tairport, depart, arrive, fare FROM flights INNER JOIN airports from_port ON (from_port.code = flights.fairport) and (to_port.code = flights.tairport) 

如果您想在FROM和TO机场search,则需要两次join机场表格 – 那么您可以在结果集中的表格中使用这两种表格:

 SELECT Flights.*,fromAirports.*,toAirports.* FROM Flights INNER JOIN Airports fromAirports on Flights.fairport = fromAirports.code INNER JOIN Airports toAirports on Flights.tairport = toAirports.code WHERE ...