是否可以将 table a 中的列与 table b 中的2列连接起来?
以下是我的情况的一个简单示例:
**Flight**
idFlight Flightnumber Date idDepart idArrival
1 5871 2018-02-03 1 2
2 5872 2018-03-08 1 3
3 5873 2018-03-19 3 2
4 5874 2018-04-11 2 1
5 5875 2018-04-21 3 2
**Airport**
idAirport Code Name
1 AMS Amsterdam Airport Schiphol
2 JFK John F Kennedy International Airport
3 TXL Berlijn Tegel Airport
我想要完成的是在一个查询中概述航班的起飞和到达地点。这是我到目前为止所得到的:
SELECT Flight.Flightnumber, Flight.Date, Airport.Name AS 'Arriving at' FROM Flight
LEFT JOIN Airport ON Flight.idArrival = Airport.idAirport
但似乎无法弄明如何在Flight.idDepart
上Airport.idAirport
创建另一个别名“离开”。两次加入机场不起作用所以我尝试使用这样的子查询:
SELECT Flight.Flightnumber, Flight.Date, Airport.Name AS 'Arriving at',
( SELECT Airport.Name AS 'Departing from' FROM Flight
LEFT JOIN Airport ON Flight.idDepart = Airport.idAirport )
FROM Flight
LEFT JOIN Airport ON Flight.idArrival = Airport.idAirport
实现这一目标的最佳方式是什么?
答案 0 :(得分:2)
您可以尝试两个左边的连接,机场1用于出发,1个用于到达,
尝试以下查询。
SELECT
f.Flightnumber,
f.date,
a.name AS dept,
a1.name AS arrvl
FROM
flight f LEFT JOIN airport a ON a.idAirport = f.idDepart
LEFT JOIN airport a1 ON a1.idAirport = f.idArrival
尝试演示Here
答案 1 :(得分:1)
这可以为您提供您正在寻找的结果集:
SELECT f.FlightNumber, f.FlightDate, d.Name AS departAirport, a.Name AS arrivalAirport
FROM Flight AS f
LEFT JOIN Airport AS d ON f.idDepart = d.idAirport
LEFT JOIN Airport AS a ON f.idArrival = a.idAirport
答案 2 :(得分:0)
您可以对每个查询进行别名,如下所示( 未经测试 ):
SELECT flights.FlightNumber, flights.FlightDate, departures.Name, arrivals.Name
FROM (SELECT * FROM Flight) AS flights
LEFT JOIN (SELECT * FROM Airport) AS departures ON flights.idDepart = departures.idAirport
LEFT JOIN (SELECT * FROM Airport) AS arrivals ON flights.idArrival = arrivals .idAIrport
答案 3 :(得分:0)
尝试相关的子查询
SELECT Flight.Flightnumber, Flight.Date, Airport.Name AS 'Arriving at',
( SELECT Airport.Name from Airport ON Flight.idDepart = Airport.idAirport) as 'Departing From'
FROM Flight
JOIN Airport ON Flight.idArrival = Airport.idAirport