SQL不同条件多选

时间:2015-01-29 19:58:12

标签: mysql sql select join left-join

我想要做的(对于每个航班),选择Flight_number,Departure_airport的名称和Arrival_airport的名称。出发时有MIN Leg_number,到达时有MAX Leg_number。

我试过这个。但是加入部分或缺少什么,这里是链接:http://sqlfiddle.com/#!2/263a2/5

2 个答案:

答案 0 :(得分:1)

看起来奇怪..但这可能就是你所追求的...... 我们得到子查询别名为“Z”的每个航班的最小/最大航段 我们使用此功能两次加入flight_leg,一次是出发,一次是抵达 并再次返回机场两次到达机场,一次到达。

 SELECT Z.Flight_Number, DA.Name DeptName, AA.Name ArrivName
    FROM (SELECT MIN(Leg_Number) MLN, MAX(Leg_Number) MxLN, Flight_Number
               FROM Flight_Leg Group by Flight_Number) Z
    INNER JOIN Flight_Leg D
     on D.Flight_Number = Z.Flight_Number 
    and D.Leg_Number = Z.MLN
    INNER JOIN Flight_Leg A
     on A.Flight_Number = Z.Flight_Number
     and A.Leg_Number = Z.MxLN
    INNER JOIN AirPort DA
     on DA.AirPort_Code = D.Departure_AirPort_Code
    INNER JOIN AirPort AA
     on AA.AirPort_Code = A.Arrival_AirPort_Code

http://sqlfiddle.com/#!2/263a2/56

答案 1 :(得分:0)

不完全确定这是否是你所追求的。它是用MS SQL编写的,因此语法需要一些小的调整。

SELECT fl.Flight_number,
ao.Name,
ai.Name,
(select min(Leg_number) from FLIGHT_LEG fa where fl.Flight_number
    = fa.Flight_number) as min_leg_number,

(select max(Leg_number) from FLIGHT_LEG fb where fl.Flight_number
    = fb.Flight_number) as max_leg_number
FROM Flight_leg Fl
inner join AIRPORT as ao on fl.Departure_airport_code =
    ao.Airport_code
inner join AIRPORT as ai on fl.Arrival_airport_code =
    ai.Airport_code