当具体的表发生特定的数据库事件时,触发器执行对应的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;
1 row in set (0.19 sec)
注:上面的打印信息是删减版的,完整的信息,可以自行在环境中查看。
mysql> DROP TRIGGER stu_trigger;
Query OK, 0 rows affected (0.01 sec)
说明删除成功了