概述:
当具体的表发生特定的数据库事件时,触发器执行对应的SQL命令。
语法:
创建触发器的一般命令如下:
CREATE [temp|temporary] trigger name
[before|after] [insert|delete|update|update of columns] ON table
action
触发器的使用:
创建:
mysql> CREATE TRIGGER stu_trigger AFTER INSERT
-> ON students
-> FOR EACH ROW
-> INSERT INTO info(stu_id, info) values (new.id, '');
Query OK, 0 rows affected (0.07 sec)
触发事件:
mysql> INSERT INTO students(id, name, age) values (4, 'Zeus', 56400);
Query OK, 1 row affected (0.00 sec)
验证students表结果:
mysql> SELECT * FROM students;
+------+----------------+--------+
| id | name | age |
+------+----------------+--------+
| 1 | bumblebee | 800 |
| 2 | king of monkey | 10000 |
| 3 | Medusa | 100000 |
| 4 | Zeus | 56400 |
+------+----------------+--------+
4 rows in set (0.00 sec)
验证info表结果:
mysql> SELECT * FROM info;
+----+--------+---------------------------------+
| id | stu_id | info |
+----+--------+---------------------------------+
| 1 | 1 | A member of the deformed steel. |
| 2 | 2 | Hero in Chinese Mythology. |
| 3 | 3 | In Greek mythology the Gorgon. |
| 5 | 4 | |
+----+--------+---------------------------------+
4 rows in set (0.00 sec)
注:这里的新id为5而不为4的原因,是因为之前对info表作了删除操作导致。
查看触发器的信息:
mysql> SELECT * FROM information_schema.triggers;
+----------------+--------------+--------------------+---------------------+
| TRIGGER_SCHEMA | TRIGGER_NAME | EVENT_MANIPULATION | EVENT_OBJECT_SCHEMA |
+----------------+--------------+--------------------+---------------------+
| student | stu_trigger | INSERT | student |
+----------------+--------------+--------------------+---------------------+
+--------------------+----------------------------------------------------+
| EVENT_OBJECT_TABLE | ACTION_STATEMENT |
+--------------------+----------------------------------------------------+
| students | INSERT INTO info(stu_id, info) values (new.id, '') |
+--------------------+----------------------------------------------------+
1 row in set (0.19 sec)
注:上面的打印信息是删减版的,完整的信息,可以自行在环境中查看。
删除触发器:
mysql> DROP TRIGGER stu_trigger;
Query OK, 0 rows affected (0.01 sec)
验证删除结果:
mysql> SELECT * FROM information_schema.triggers;Empty set (0.01 sec)
说明删除成功了
来源:https://www.cnblogs.com/fengju/p/6336080.html