什么是触发器
就是trigger(扳机), 一碰就动, 一触即发, 就叫触发器
跟存储过程类似, 也是主要用于增, 删, 改
事先为某张表绑定一段代码, 当表中的某些内容发生改变的时候(对表进行增删改), 系统就会自动触发代码执行
监听, 只要...就触发, 然后执行...
为什么需要触发器?
有些sql语句, 或者数据库操作, 在逻辑上是紧密相关, 不可分割的, 需要一起执行
创建触发器
我们需要一些测试数据
drop database if exists mail;
create database mail character set utf8;
use mail;
create table goods(
goods_id int primary key,
goods_name varchar(20) not null,
goods_inventory int not null
);
create table orders(
orders_id int primary key,
orders_goods_id int not null,
orders_buy_number int not null,
foreign key(orders_goods_id) references goods(goods_id)
);
insert into goods set goods_id = 1, goods_name = 'television', goods_inventory = 20;
insert into goods set goods_id = 2, goods_name = 'bicyle', goods_inventory = 99;
insert into orders set orders_id = 1, orders_goods_id = 1, orders_buy_number = 2;
insert into orders set orders_id = 2, orders_goods_id = 2, orders_buy_number = 10;
insert
insert之前(语法)
drop trigger if exists 插入前触发;
create trigger 插入前触发 before insert on teacher for each row
-- sql语句, 不能是select
begin
end;
insert之后(语法)
drop trigger if exists 插入后触发;
create trigger 插入后触发 after insert on teacher for each row
begin
-- sql语句, 不能是select
end;
我们的需求, 当订单表里新增订单之后, 商品表里的库存需要相应减少
drop trigger if exists change_inventory;
create trigger change_inventory after insert on orders for each ROW begin
update goods
set
goods_inventory = goods_inventory - new.orders_buy_number
where
goods_id = new.orders_goods_id;
end;
insert into orders
set
orders_id = 3,
orders_goods_id = 1,
orders_buy_number = 3;
delete
如果订单取消, 商品的库存应该恢复
我们编写一个触发器, 如果订单取消, 则电视机的库存恢复到原来的20
drop trigger if exists recover_inventory;
create trigger recover_inventory after delete on orders for each row begin
update goods
set goods_inventory = goods_inventory + old.orders_buy_number
where goods_id = old.orders_goods_id;
end;
delete from orders where orders_id = 3;
查看触发器
查看所有触发器
show triggers;
查看触发器创建语句
show create trigger 触发器名称;
删除&修改触发器
触发器不能修改, 只能先删除, 再修改
drop trigger 触发器名称;
最后说明
- 触发器中, 只能有增删改, 不能有查
- 触发器中只能对非监听的表, 进行增删改, 避免死循环
- 触发器的监听对象,并不都有new和old
trigger监听对象