[MySQL]触发器
案列:从新订单表添加购买或退货的数量,然后从goods表总数中增加或减少?
create trigger TriggerName
after/before 触发时间
insert/update/delete 监控事件
on 表名
for each row
begin
sql1;
...
sqlN;
end
创建goods表:
create table goods
(
git int
, name varchar(20)
, num smallint
)
;
创建ord表:
create table ord
(
oid int
, gid int
, much smallint
)
;
插入goods表种类数据:
insert into goods values
(1
,'cat', 34
)
,
(2
,'dog', 65
)
,
(3
,'pig', 21
)
;
简单触发器 insert delete update:
delimiter $
create trigger goods_ord_insert after
insert
on
ord for each row begin
update
goods
set num=num-new.much
where
gid=new.gid
;
end$
delimiter $
create trigger goods_ord_dele after
delete
on
ord for each row begin
update
goods
set num=num+old.much
where
gid=old.gid
;
end$
delimiter $
create trigger update_
before
update
on ord
for each row
begin
update goods set num=num+old.much-new.much where gid=new.gid;
end$
触发器升级版:
如果剩余数量不足则只能卖出剩余数量;
before 在内存中修改之前做判断还未写到硬盘中;
after 在内存中修改之后写到硬盘后再去执行;
select
num
into rnum
from
goods
where
gid=new.gid
;
if new.much >rnum then
set new.much=rnum;
end if;
update
goods
set num=num-new.much
where
gid=new.gid
;
end$
for each row 行级触发器
遗憾mysql 不支持语句级触发器。