MySQL创建触发器

来源: 2024-07-06 17:19:00 播报

触发器创建流程,首先触发器是创建在永久表上,所以先创建表,后在对该表创建触发器

案例:创建简单触发器

一、准备学生表和学生数目统计表

CREATE TABLE student_info (
stu_no INT(11) NOT NULL AUTO_INCREMENT,
stu_name VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (stu_no)
);
CREATE TABLE student_count (
student_count INT(11) DEFAULT 0
);
INSERT INTO student_count VALUES(0);

二、创建简单触发器,在向学生表INSERT数据时,学生数增加,DELETE学生时,学生数减少

CREATE TRIGGER trigger_student_count_insert
AFTER INSERT
ON student_info FOR EACH ROW
UPDATE student_count SET student_count=student_count+1;
CREATE TRIGGER trigger_student_count_delete
AFTER DELETE
ON student_info FOR EACH ROW
UPDATE student_count SET student_count=student_count-1;

三、INSERT、DELETE数据,查看触发器是否正常工作

mysql> INSERT INTO student_info VALUES(NULL,'张明'),(NULL,'李明'),(NULL,'王明');
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0
mysql> SELECT * FROM student_info;
+--------+----------+
| stu_no | stu_name |
+--------+----------+
|      1 | 张明     |
|      2 | 李明     |
|      3 | 王明     |
+--------+----------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM student_count;
+---------------+
| student_count |
+---------------+
|             3 |
+---------------+
1 row in set (0.00 sec)
mysql> DELETE FROM student_info WHERE stu_name IN('张明','李明');
Query OK, 2 rows affected (0.00 sec)
mysql> SELECT * FROM student_info;
+--------+----------+
| stu_no | stu_name |
+--------+----------+
|      3 | 王明     |
+--------+----------+
1 row in set (0.00 sec)
mysql> SELECT * FROM student_count;
+---------------+
| student_count |
+---------------+
|             1 |
+---------------+
1 row in set (0.00 sec)

可以看到无论是INSERT还是DELETE学生,学生数目都是跟随着变化的。