MySQL/mariadb知识点——触发器
触发器
触发器:trigger
,是指事先为某张表绑定一段代码,当表中的某些内容发生改变(增、删、改)的时候,系统会自动触发代码并执行。
触发器包含三个要素,分别为
- 事件类型:增删改,即
insert
、delete
和update
- 触发时间:事件类型前和后,即
before
和after
- 触发对象:表中的每一条记录(行),即
整张表
每张表只能拥有一种触发时间的一种事件类型的触发器,即每张表最多可以拥有 6 种触发器;即:BEFORE INSERT、BEFORE UPDATE、BEFORE DELETE、AFTER INSERT、AFTER UPDATE、AFTER DELETE。
创建触发器
创建触发器语法如下
mysql CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body
其中:
trigger_name:标识触发器名称,用户自行指定;
trigger_time:标识触发时机,取值为 BEFORE 或 AFTER;
trigger_event:标识触发事件,取值为 INSERT、UPDATE 或 DELETE;
tbl_name:标识建立触发器的表名,即在哪张表上建立触发器;
trigger_stmt:触发器程序体,可以是一句SQL语句,或者用 BEGIN 和 END 包含的多条语
查看触发器
和查看数据库(show databases;)查看表格(show tables;)一样,查看触发器的语法如下:
SHOW TRIGGERS;
删除触发器
和删除数据库、删除表格一样,删除触发器的语法如下:
DROP TRIGGER trigger_name;
示例
创建触发器,在向学生表INSERT数据时,学生数增加,删除学生信息时,学生数减少。
MariaDB [testdb]> CREATE TABLE students_info (id TINYINT(2) NOT NULL AUTO_INCREMENT,name VARCHAR(30) DEFAULT NULL,PRIMARY KEY(id)); #创建一张学生信息表 MariaDB [testdb]> CREATE TABLE students_count (stu_count TINYINT(2) DEFAULT 0); #创建一张学生数量表 MariaDB [testdb]> INSERT INTO students_count VALUES(0); #给个初识值0 MariaDB [testdb]> CREATE TRIGGER trigger_students_count_insert -> AFTER INSERT -> ON students_info FOR EACH ROW -> UPDATE students_count SET stu_count=stu_count+1; Query OK, 0 rows affected (0.00 sec) MariaDB [testdb]> CREATE TRIGGER trigger_students_count_delete -> AFTER DELETE -> ON students_info FOR EACH ROW -> UPDATE students_count SET stu_count=stu_count-1; Query OK, 0 rows affected (0.01 sec)
MariaDB [testdb]> INSERT students_info(id,name) VALUES (1,'Tom'),(2,'Maria'); MariaDB [testdb]> SELECT * FROM students_info; +----+-------+ | id | name | +----+-------+ | 1 | Tom | | 2 | Maria | +----+-------+ MariaDB [testdb]> SELECT * FROM students_count; #插入记录,触发事件,数量增加为2 +-----------+ | stu_count | +-----------+ | 2 | +-----------+ MariaDB [testdb]> DELETE FROM students_info WHERE id=1; MariaDB [testdb]> SELECT * FROM students_info; +----+-------+ | id | name | +----+-------+ | 2 | Maria | +----+-------+ MariaDB [testdb]> SELECT * FROM students_count; #删除记录,数量减1 +-----------+ | stu_count | +-----------+ | 1 | +-----------+