MySQL JOIN两行合二为一?

时间:2013-08-02 01:39:19

标签: mysql join

如何创建一个查询,从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)中为每个航班命中数据库?虽然我可以这样做,但查询解决方案会更优雅并且使用更少的资源。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分: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;

这可确保该对按字母顺序排列。 。 。所以输出中只有一对。

答案 1 :(得分:0)

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

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;