Home >Database >Mysql Tutorial >MySQL数据库触发器(trigger)_MySQL

MySQL数据库触发器(trigger)_MySQL

WBOY
WBOYOriginal
2016-06-01 13:01:341249browse

MySQL触发器(trigger):监视某种情况并触发某种操作

一:四要素

触发时间:before/after

地点:table

监视操作:insert/update/delete

触发操作:insert/update/delete

二:创建触发器

delimiter $ #将sql结束符改为$ 方便写触发的sql语句

create trigger triggerName after/before insert/update/delete on tableName

for each row

begin

sql语句; #想要触发的语句

end$

测试表:商品表(g),订单表(o)

三:删除监视器

drop trigger triggerName

四:下定单(o),商品表(g)数据触发更新

create trigger tg after insert on o

for each row

begin

update g set num=num-new.much where id=new.gid;

end$

PS:对于监视操作insert 而言,新增的行用new 表示

行中的每一列的值,用new.列名 取出

五:删除一个订单,商品表相应增加

create trigger tg after delete on o

for each row

begin

update g set num=num+old.much where id=old.gid;

end$

六:修改一个订单,商品表相应改变

create trigger tg after update on o

for each row

begin

update g set num=num+old.much-new.much where id=old.gid;

end$

七:after与before区别

after 是先完成数据的增删改,再触发,前面的数据操作完成

before是先触发,判断触发的条件是否满足,再对数据进行增删改操作

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn