如何编写 function/trigger 从布尔表达式的查询中获取单个值

How to write function/trigger that grabs single values from queries for a boolean expression

我正在使用 javascript 和 postgres 数据库开发模拟机票预订应用程序。

--已编辑--

我需要创建一个 function/trigger,如果航班的机票数量不超过飞机的最大座位数,它只允许我在我的 TICKET 中插入一个新行。

如何编写一个函数来将单个值与查询隔离开来: 1)SELECT count(*) FROM ticket WHERE flight_id = x 2)SELECT maxSeats FROM airplane 其中 aircraft_code =(与航班相关的飞机代码)。

如何从这两个查询中获取单个值以进行检查(座位数 <= max_seats)。

谢谢。

I need to do a transaction that does the following: -INSERT new row in TICKET table that includes a foreign key(flight_id) that references the FLIGHT table. -UPDATE the number of seats(increment by one) in the FLIGHT table for the flight(flight_id) that the ticket was just inserted.

您可以通过SELECT COUNT(*) FROM TICKET WHERE flight_id = {flight_id}推导出“座位数”。在 FLIGHT 中添加 number of seats 属性会导致规范化错误,并迫使您使其与 FLIGHT 的 TICKET 保持同步。

Do I need to use a trigger or function for this that will simply throw an error when I try to commit? or is there a way to set up a special kind of constraint for a column that references the value in another table(ie. FLIGHT.num_seats_booked < AIRPLANE.max_num_seats.)

在支持它的平台中,您可以添加一个 CHECK 约束,该约束调用一个函数通过查询其他表来进行必要的检查。据我所知,虽然您可以在 Postgres 中执行此操作,但并发更新存在问题,建议使用触发器。

I need to only commit the above transaction if their are still seats available for the flight.

Or should I be using an IF/ELSE query inside of my transaction?

Just looking to get pointed in the general right direction on how to approach this kind of problem

与 Postgres 无关,但如果您感兴趣,请查看 this 帖子


How do i go about writing a function that compares number of tickets for a flight and max_seats for an airplane? I'm not sure how to grab a single value from two queries to compare them and return true or false in a function.

像这样的东西会起作用:

SELECT COUNT(*) < (
    SELECT MaxSeats
    FROM Flight
    INNER JOIN Aircraft
    ON Aircraft.AircraftCode = Flight.AircraftCode
    WHERE FlightId = {flightId})    
FROM Ticket
WHERE FlightId = {flightId}