drop trigger if exists payment_after_insert;
delimiter $$
create trigger payment_after_insert
after insert on payments -- 还可写update / delete
for each row -- 触发器会作用于每一个受影响的行
begin
update invoices
set payment_total = payment_total + new.amount
where invoice_id = new.invoice_id;
end $$
delimiter ;
insert into payments
values (default, 5, 3, '2019-01-01', 10, 1)
结果:原来id为3的total是0,触发器后自动更新为10
drop trigger if exists payment_after_delete;
delimiter $$
create trigger payments_after_delete
after delete on payments
for each row
begin
update invoices
set payment_total = payment_total - old.amount
where invoice_id = old.invoice_id;
end $$
delimiter ;
delete from payments
where payment_id = 9;
结果:
-- 查看所有触发器
show triggers
-- 按条件筛选查看触发器
show triggers like 'payments%'
-- 在插入数据后,进行操作的记录
drop trigger if exists payment_after_insert;
delimiter $$
create trigger payment_after_insert
after insert on payments
for each row -- 触发器会作用于每一个受影响的行
begin
update invoices
set payment_total = payment_total + new.amount
where invoice_id = new.invoice_id;
-- 往记录操作的表里插入一条数据,类型为插入
insert into payments_audit
values (new.client_id, new.date, new.amount, 'Insert', now());
end $$
delimiter ;
drop trigger if exists payments_after_delete;
delimiter $$
create trigger payments_after_delete
after delete on payments
for each row
begin
update invoices
set payment_total = payment_total - old.amount
where invoice_id = old.invoice_id;
-- 往记录操作的表里插入一条数据,类型为删除
insert into payments_audit
values (old.client_id, old.date, old.amount, 'Delete', now());
end $$
delimiter ;
insert into payments
values (default, 5, 3, '2019-01-01', 10, 1);
delete from payments
where payment_id = 10;
运行结果:payments_audit表中记录了两条操作记录
drop event if exists yearly_delete_stale_audit_rows;
delimiter $$
create event yearly_delete_stale_audit_rows
on schedule
every 10 second starts '2019-01-01' ends '2029-01-01'
do begin
delete from payments_audit
where action_date < now() - interval 5 minute;
end $$
delimiter ;
结果:创建事件前,audit表的数据:
创建时间后,删除了表中的数据