时间:2021-07-01 10:21:17 帮助过:75人阅读
create trigger test1 #触发器名称 (after/before) #触发时间 (insert/update/delete) #监视事件 on table #监视地点(表名) for each row #mysql必须加的 begin sql1 ... sqlN end; #end$$查询已有trigger:show triggers 删除已有trigger:drop trigger 触发器名称 new/old: update触发:old 代表更新前的记录。new 代表更新后的记录. insert触发:old 不能使用。new 代表插入的记录. delete触发:old 代表删除的记录。new 不能使用.
CREATE TABLE goods( `goods_id` INT(10), `name` VARCHAR(20), `num` SMALLINT(4) )ENGINE=INNODB CHARSET=utf8 CREATE TABLE `ord`( `oid` INT(10), `gid` INT(10), `much` INT(10) )ENGINE=INNODB CHARSET=utf8 INSERT INTO goods VALUES (1, 'cat', 26),(2, 'dog', 26),(3, 'pig', 26);1、要求每下一个订单,goods表中的库存相应减少订单的数量。 mysql> select * from goods +----------+------+------+ | goods_id | name | num | +----------+------+------+ | 1 | cat | 26 | | 2 | dog | 26 | | 3 | pig | 26 | +----------+------+------+ 3 rows in set (0.00 sec) mysql> select * from ord; Empty set (0.00 sec)
#创建触发器test1 DELIMITER $$ CREATE TRIGGER test1 AFTER INSERT ON `ord` FOR EACH ROW BEGIN UPDATE goods SET num= num - new.much WHERE goods_id = new.gid; END$$
#触发器test2 CREATE TRIGGER test2 AFTER DELETE ON `ord` FOR EACH ROW BEGIN UPDATE goods SET num = num + old.much WHERE goods_id = old.gid; END $$
#触发器test3 CREATE TRIGGER test3 AFTER UPDATE ON `ord` FOR EACH ROW BEGIN UPDATE goods SET num = num + old.much - new.much WHERE goods_id = new.gid; END$$