– 可以把这两个业务逻辑看成一个整体。业务逻辑时紧密相连的,不可分割的,这时候可以选择触发器
– 触发器是一类特殊的事务 ,
– 可以监视某种数据操作(insert/update/delete),
– 并触发相关操作(insert/update/delete)
– 触发器:trigger
– 中文:一触即发
– 触发器只能监视增删改
– 只能触发增删改
create table g(
gid int not null,
gname varchar(20),
much INT
)charset=utf8,ENGINE=INNODB;
create table o(
oid int not null,
oname varchar(20),
sum INT
)charset=utf8,ENGINE=INNODB;
insert into o VALUES(3,2,1);
select * from g;
INSERT INTO g values(1,‘电脑’,18);
INSERT INTO g values(2,‘手机’,15);
INSERT INTO g values(3,‘水杯’,30);
INSERT INTO g values(4,‘鼠标’,10);
INSERT INTO g values(5,‘矿泉水’,50);
select * from g;
– 未使用触发器
INSERT into o VALUEs(1,1,2);
update g set much=much-2 where gid=1;
– 如果我下了10万个订单 同时得写10万个update,
– 中间可能会出现库存数量加错或减错的问题
– 第一个触发器
create trigger mycf1
AFTER – 触发时间
insert – 监视事件
on o – 监视地点
for each ROW
BEGIN
– 触发事件
update g set much=much-2 where gid=1;
end
INSERT into o VALUEs(2,1,2);
insert into o VALUES(3,2,1);
select * from g;
select * from o;
– 删除触发器
DROP TRIGGER mycf1;
– 创建触发器的语法
– create trigger 触发器名称
– after/before (触发时间)
– insert/update/delete (监视事件)
– FOR EACH ROW
– on 表名 (监视地址)
– for each row
– begin
– sql1;
– …
– sqlN;
– End
– 添加的触发器:
– 添加了一个订单,在订单表新增了一条新的数据 新增的数据用new表示
create trigger mycf2
AFTER INSERT ON o
for EACH ROW
BEGIN
update g set much=much-new.num where gid=new.gid;
end;
select * from g;
select * from o;
INSERT into o values(4,5,10);
– 删除订单:库存数量+订单的购买数量
– 删除就是删除一条旧的行 用old表示
CREATE TRIGGER mycf3
AFTER DELETE on o
for EACH ROW
BEGIN
update g set much=much+old.num where gid=old.gid;
END
select * from g;
select * from o;
delete from o where oid=1;
delete from o where oid=4;
– 修改
create TRIGGER mycf4
AFTER UPDATE on o
FOR EACH ROW
BEGIN
update g set much=much+old.num-new.num where gid=new.gid;
END
– 库存数量10 下的订单的数量2 把订单数量改成4
– 10-2=8 10+2-4=8;
select * from g;
select * from o;
update o set num=4 where oid=2;
update o set num=1 where oid=2;