MySQL 在插入触发器后更新另一个表的列
创建预订请求时,需要根据以下数据更新 BookingRequest 表中的状态将相应的请求插入 OccupiedRoom 表中。为此,需要一个触发器。
首先,定义以下表:
<br> -- BookingRequest 表:<br> CREATE TABLE BookingRequest (<pre class="brush:php;toolbar:false">idRequest INT NOT NULL AUTO_INCREMENT, roomClass INT NOT NULL, inDate DATE NOT NULL, outDate DATE NOT NULL, numOfBeds INT NOT NULL, status INT NOT NULL, idUser INT NOT NULL, PRIMARY KEY (idRequest), INDEX idx_status (status), INDEX idx_user (idUser)
);
--状态表:
CREATE TABLE Status (
idStatus INT NOT NULL AUTO_INCREMENT, nameStatus ENUM('underConsideration', 'approved', 'rejected'), PRIMARY KEY (idStatus)
);
-- OccupiedRoom 表:
CREATE TABLE OccupiedRoom (
idOccupation INT NOT NULL AUTO_INCREMENT, idRoom INT NOT NULL, idRequest INT NOT NULL, PRIMARY KEY (idOccupation), INDEX idx_id_room (idRoom), INDEX idx_id_request (idRequest)
);
前>
现在,让我们编写触发器:
DELIMITER $$ CREATE TRIGGER occupy_trig AFTER INSERT ON `OccupiedRoom` FOR EACH ROW begin DECLARE id_exists Boolean; -- Check BookingRequest table SELECT 1 INTO @id_exists FROM BookingRequest WHERE BookingRequest.idRequest= NEW.idRequest; IF @id_exists = 1 THEN UPDATE BookingRequest SET status = '1' WHERE idRequest = NEW.idRequest; END IF; END; $$ DELIMITER ;
它的工作原理如下:
以上是如何使用 MySQL 触发器插入 OccupiedRoom 后更新 BookingRequest 状态?的详细内容。更多信息请关注PHP中文网其他相关文章!