带有子查询的MariaDB视图

时间:2019-01-22 19:12:22

标签: sql mariadb

对于我们大学的作业,我应该针对数据库创建一个视图,但是有一个约束,即它只能是一个陈述。 而那句话的一部分现在让我头疼。

我创建了以下语句:

CREATE VIEW overbook_future_flights AS
SELECT 
    FlightNo,
    DepartureDateAndTimeUTC,
    ICAO_Code_Origin,
    ICAO_Code_Destination,
    PlaneID,
    NoOfSeats,
    NoOfReservedSeats AS NoReservedSeats
FROM (
    SELECT
        flightexecution.ICAO_Code_Origin,
        flightexecution.ICAO_Code_Destination,
        CURRENT_TIMESTAMP() AS nowUTC,
        SUM(NoReservedSeats) AS NoOfReservedSeats,
        flightexecution.DepartureDateAndTimeUTC,
        reservation.FlightNo,
        plane.PlaneID,
        plane.NoOfSeats
    FROM reservation
    INNER JOIN flightexecution ON
        flightexecution.FlightNo = reservation.FlightNo AND
        flightexecution.DepartureDateAndTimeUTC = reservation.DepartureDateAndTimeUTC
    INNER JOIN plane ON
        flightexecution.PlaneID = plane.PlaneID
    GROUP BY
        FlightNo,
        DepartureDateAndTimeUTC
    HAVING
        NoOfreservedSeats > NoOfSeats and
        nowUTC < DepartureDateAndTimeUTC
) AS a;

但是它失败了,因为create view不允许from语句内的子查询。 通常,我只会创建多个视图并使用该视图而不是子查询,但这应该只是一个语句。

有人知道这个作业是否可以解决?如果是,该如何解决?

1 个答案:

答案 0 :(得分:1)

MySQL历史上(因此,MariaDB)不允许FROM中的子查询。幸运的是,您不需要一个:

CREATE VIEW overbook_future_flights AS
    SELECT fe.FlightNo, fe.DepartureDateAndTimeUTC,
           ?.ICAO_Code_Origin, ?.ICAO_Code_Destination, fe.PlaneID,
           p.NoOfSeats,
           SUM(r.NoReservedSeats) as NoOfReservedSeats
    FROM reservation r JOIN
         flightexecution fe
         ON fe.FlightNo = r.FlightNo AND
         fe.DepartureDateAndTimeUTC = r.DepartureDateAndTimeUTC JOIN
         plane p
         ON fe.PlaneID = p.PlaneID
    WHERE CURRENT_TIMESTAMP < DepartureDateAndTimeUTC
    GROUP BY fe.FlightNo, fe.DepartureDateAndTimeUTC,
             ?.ICAO_Code_Origin, ?.ICAO_Code_Destination, fe.PlaneID,
             p.NoOfSeats
    HAVING NoOfreservedSeats > p.NoOfSeats;

填写?的适当别名。我可能猜错了一些桌子。

注意:

  • 表别名使查询更易于编写和阅读。
  • 使用适当的别名限定所有列名称。
  • 所有未聚合的列应位于GROUP BY中。