Mysql触发器在更新时保留cloumn子容量if语句

时间:2018-02-28 09:12:38

标签: mysql sql triggers

我想设置检查类容量,如果全班应该是   确认。当我更新保留时,它会给出错误。请帮忙。谢谢。

CREATE TRIGGER `control_class_capacity` 
AFTER UPDATE ON  `learningcenter_class`
FOR EACH ROW BEGIN

IF NEW.capacity - NEW.reserved = 0 THEN BEGIN

UPDATE learningcenter_class SET isconfirm = 1 WHERE class_id = NEW.class_id;

END; END IF;
END

1 个答案:

答案 0 :(得分:0)

假设您的class_id是唯一的,您可以将触发器更改为before触发器并设置NEW.ISCONFIRM。 BTW如果MYSQL中的语句不需要开始和结束语句。

drop table if exists t;
create table t(class_id int ,capacity int, reserved int, isconfirm int);
insert into t values (1,1,0,0) , (2,1,0,0);

drop trigger if exists `control_class_capacity`;
delimiter $$
CREATE TRIGGER `control_class_capacity` 
before UPDATE ON  t
FOR EACH ROW BEGIN

IF NEW.capacity - NEW.reserved = 0 THEN

SET new.isconfirm = 1;

END IF;
END $$

delimiter ;

update t set reserved = 1 where class_id = 1;

select * from t;

+----------+----------+----------+-----------+
| class_id | capacity | reserved | isconfirm |
+----------+----------+----------+-----------+
|        1 |        1 |        1 |         1 |
|        2 |        1 |        0 |         0 |
+----------+----------+----------+-----------+
2 rows in set (0.00 sec)