1

我正在用 php 创建房间预订。

我有两张桌子:

桌子RESERVE

  • Reserve_id
  • room_id
  • room_reserve_qty
  • 查看

桌子ROOM

  • room_id
  • 房间数量

当“结帐”日期达到今天的日期时,保留表中的该行将被删除。实际上我已经有该事件:

DROP EVENT `auto_delete_chckout`;
CREATE DEFINER=`root`@`localhost` 
EVENT `auto_delete_chckout` 
ON SCHEDULE EVERY 1 MINUTE STARTS '2013-01-26 13:09:15' 
ON COMPLETION NOT PRESERVE ENABLE DO 
DELETE FROM reserve WHERE checkout <= CURDATE()

所以我的问题是:

如果要删除预订,则room_reserve_qty 必须将其添加room_qty房间表中。

4

2 回答 2

1

在删除 table 上的记录之前reserve,您需要先更新 table 的记录,room以便您知道哪些room_id将被更新,例如

UPDATE  room a
        INNER JOIN reserve b
            ON a.room_id = b.room_id
SET     a.room_qty = a.room_qty + b.room_reserve_qty
WHERE   b.checkout <= CURDATE();

DELETE FROM reserve WHERE checkout <= CURDATE();

完整代码:

DROP EVENT `auto_delete_chckout`;
DELIMITER $$
CREATE EVENT `auto_delete_chckout` 
    ON SCHEDULE EVERY 1 MINUTE STARTS '2013-01-26 13:09:15' 
    ON COMPLETION NOT PRESERVE ENABLE 
    DO 
        BEGIN
            UPDATE  room a
                    INNER JOIN reserve b
                        ON a.room_id = b.room_id
            SET     a.room_qty = a.room_qty + b.room_reserve_qty
            WHERE   b.checkout <= CURDATE();

            DELETE FROM reserve WHERE checkout <= CURDATE();
        END $$
DELIMITER ;

更新

既然你提到你是新人,Event认为这会导致服务器上的大量工作。ATRIGGER可能是另一种方式。ATrigger基本上是每次在桌子上发生事件(之前或之后INSERT)时触发的代码块,例如:UPDATEDELETE

于 2013-01-27T05:05:48.203 回答
0

首先,您可能不需要每分钟触发您的事件,因为您只检查日期部分。您可能希望每天执行一次。

其次,我会将更新room_qty逻辑放在触发器中。这样,无论您如何删除预订,您room_qty都是正确的。

您的触发器可能如下所示

DELIMITER $$

CREATE TRIGGER reserve_before_delete BEFORE DELETE ON reserve
    FOR EACH ROW BEGIN
        UPDATE room
           SET room_qty = room_qty + OLD.room_reserve_qty 
         WHERE room_id = OLD.room_id;
    END;
$$

DELIMITER ;

DELETE当您使用触发器时,您的代码保持不变。

于 2013-01-27T05:12:30.780 回答