根据第一个查询答案加入两个SQL查询

时间:2017-04-14 11:57:01

标签: mysql sql database join subquery

我一直在寻找各地,这将是向别人寻求帮助的最佳网站。我必须进行SQL查询,检查特定航班的预订总量,然后根据系统应提供飞机选择的预订数量。第一个查询工作,它发现预订总数,我认为我有案例声明权利选择一架飞机,但我无法找到物理连接两个查询的方式,我试图使用unison,内部连接和嵌套查询,但它似乎预订的总座位数(第一次查询的答案)无法找到,请帮助我们。

第一个SQL查询(查找预订总数)

SELECT count(bookingdetails.FlightID)AS TotalNumberOfSeatsBooked,flightdetails.FlightID
FROM  bookingdetails, bookingdetails AS TEMP,flightdetails
WHERE bookingdetails.BookingID = TEMP.BookingID
AND bookingdetails.FlightID= flightdetails.FlightID
Group BY FlightID;

第二次SQL查询(根据预订量选择一种飞机类型)

    SELECT CASE chooseaircraft
    WHEN TotalNumberOfSeatsBooked <= 110 THEN 'BA 146-200'
    ELSE'Embraer 170'
    END AS ChoiceOfAircraft
    FROM aircrafttype;

非常感谢大家 在一个答案之后,我认为我正朝着正确的方向将两个查询合并在一起,代码现在显示了子查询中的座位总数和航班号,但是飞机列的选择仍然没有显示但是如果你运行通过它自我查询我知道我接近得到这个,我将不胜感激任何帮助在SQL中变得更好我现在的代码是:

SELECT count(bookingdetails.FlightID)AS TotalNumberOfSeatsBooked,flightdetails.FlightID
FROM  bookingdetails, bookingdetails AS TEMP,flightdetails
WHERE  bookingdetails.BookingID = TEMP.BookingID
AND bookingdetails.FlightID= flightdetails.FlightID
AND bookingdetails.FlightID= flightdetails.FlightID IN(
SELECT CASE WHEN count(bookingdetails.FlightID) <= 110 THEN 'BA 146-200'
ELSE'Embraer 170' 
END AS ChoiceOfAircraft
FROM bookingdetails,flightdetails)
Group BY FlightID;

1 个答案:

答案 0 :(得分:0)

您可以在count(bookingdetails.FlightID)语句中使用相同的表达式CASE(或)将您的第一个查询包装在子查询中,并访问外部查询中的列。那是

CASE WHEN count(bookingdetails.FlightID) <= 110 THEN 'BA 146-200'
ELSE'Embraer 170'
END AS ChoiceOfAircraft