MySQL 触发器(Triggers)
在MySQL中,触发器(trigger)是一段绑定于table上的sql程序(stored program),这段程序在对表(db table)进行数据操作(insert, update, delete)时候触发并自动执行。
标准SQL定义了两种trigger类型:
- row level trigger
- statement level trigger
MySQL仅支持 row level trigger。
创建 Trigger
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE| DELETE }
ON table_name FOR EACH ROW
BEGIN
trigger_body;
END
- tigger的名字需要在数据库级别唯一;
示例
use mysql_practice;
drop table if exists customer_audit;
create table customer_audit
(
id int auto_increment primary key,
customer_no varchar(50),
first_name varchar(100),
changed_date datetime,
action varchar(50)
);
DROP TRIGGER IF EXISTS before_customer_update;
DELIMITER $$
CREATE TRIGGER before_customer_update
BEFORE UPDATE ON customer
FOR EACH ROW
BEGIN
INSERT INTO customer_audit(customer_no, first_name, changed_date, action)
values(OLD.no, OLD.first_name, now(), 'update');
INSERT INTO customer_audit(customer_no, first_name, changed_date, action)
values(NEW.no, NEW.first_name, now(), 'updated');
END $$
DELIMITER ;
调用更新customer
表语sql句:
update customer set first_name = concat(first_name, '_u') where id = 3;
更新成功后,查看 customer_audit
表数据,会插入两条新数据。
创建多triggers
MySQL 版本需要 5.7.2+
在MySQL 5.7.2之前,在db table对一个event只能创建一个trigger。
DELIMITER $$
CREATE TRIGGER trigger_name
{BEFORE|AFTER}{INSERT|UPDATE|DELETE}
ON table_name FOR EACH ROW
{FOLLOWS|PRECEDES} existing_trigger_name
BEGIN
-- statements
END$$
DELIMITER ;
查看数据库的triggers
show triggers in mysql_practice;
show triggers from mysql_practice;
show triggers from mysql_practice like 'custom%'; -- like匹配表名
如果是多triggers,想查看action order,可以:
SELECT
trigger_name,
action_order
FROM
information_schema.triggers
WHERE
trigger_schema = 'mysql_practice'
ORDER BY
event_object_table ,
action_timing ,
event_manipulation;