0

如何进行查询,从 1 行中选择大部分数据,但将一列与另一列连接起来?

一张表“flight_schedules”有:

Flight | Dep_City | Arr_ City | Dep_Time | Arr_Time
---------------------------------------------------
901    | Chicago  | Miami     | 0600     | 0900
902    | Miami    | Chicago   | 0945     | 1300

另一个表“机场”有:

City     | Airport_Code
-----------------------
Chicago  | KORD
Miami    | KMIA

我的查询 atm 是这样的:

SELECT ap.Airport_Code as dep_code, ap.Airport_Code as arr_code, fs.* FROM flight_schedules fs JOIN aiports ap ON (fs.Dep_City=ap.City OR fs.Arr_City=ap.City) ORDER BY flight_number

我知道这给了我每次飞行 2 行这样的:

arr_code | dep_code | Flight | Dep_City | Arr_ City | Dep_Time | Arr_Time
-------------------------------------------------------------------------
KORD     | KORD     | 901    | Chicago  | Miami     | 0600     | 0900
KMIA     | KMIA     | 901    | Chicago  | Miami     | 0600     | 0900
KMIA     | KMIA     | 902    | Miami    | Chicago   | 0945     | 1300
KORD     | KORD     | 902    | Miami    | Chicago   | 0945     | 1300

我真正追求的是:

arr_code | dep_code | Flight | Dep_City | Arr_ City | Dep_Time | Arr_Time
-------------------------------------------------------------------------
KORD     | KMIA     | 901    | Chicago  | Miami     | 0600     | 0900
KMIA     | KORD     | 902    | Miami    | Chicago   | 0945     | 1300

有没有办法调整我的查询来实现这一点,还是我注定要在 flight_schedules 表中包含机场代码(这需要一些脚本)?或者...为 flight_schedules 表中的每个航班(大约 3000 个)点击数据库?虽然我可以这样做,但查询解决方案会更优雅并且使用更少的资源。

提前感谢您的帮助。

4

2 回答 2

1

您想加入两次表格以分别获取到达城市和出发城市的代码:

SELECT apdep.Airport_Code as dep_code, aparr.Airport_Code as arr_code, fs.*
FROM flight_schedules fs JOIN
     aiports apdef
     ON fs.Dep_City = apdef.City join
     airports aparr
     on fs.Arr_City = aparr.City
ORDER BY flight_number;

编辑:

如果您正在寻找每个航班的一行,则添加一个where子句:

SELECT apdep.Airport_Code as dep_code, aparr.Airport_Code as arr_code, fs.*
FROM flight_schedules fs JOIN
     aiports apdef
     ON fs.Dep_City = apdef.City join
     airports aparr
     on fs.Arr_City = aparr.City
WHERE dep_city < arr_city
ORDER BY flight_number;

这确保了这对是按字母顺序排列的。. . 所以只有一对将在输出中。

于 2013-08-02T01:43:27.737 回答
0

再次感谢戈登。我尝试了 EDIT 但它并没有真正改变太多所以我尝试了这个并得到了我想要的......

SELECT DISTINCT fs.id, apdep.Airport_Code as dep_code, aparr.Airport_Code as arr_code, fs.*
FROM flight_schedules fs JOIN
 aiports apdef
 ON fs.Dep_City = apdef.City join
 airports aparr
 on fs.Arr_City = aparr.City
ORDER BY flight_number;
于 2013-08-02T04:51:57.357 回答