MySQL触发器是否激活其他触发器?

时间:2014-11-29 00:38:53

标签: mysql database triggers relational-database relationship

例如,如果我在删除该帖子时定义了删除帖子的所有评论的触发器。删除用户时删除所有帖子的触发器是否会激活另一个触发器,从而删除注释?

1 个答案:

答案 0 :(得分:3)

简短回答是是。

演示:

mysql> create table users (id serial primary key);

mysql> create table posts (id serial primary key, userid bigint unsigned);

mysql> create table comments (id serial primary key, postid bigint unsigned);

mysql> create trigger udel after delete on users for each row delete from posts where userid = OLD.id;

mysql> create trigger pdel after delete on posts for each row delete from comments where postid = OLD.id;

mysql> insert into users values (123);
Query OK, 1 row affected (0.00 sec)

mysql> insert into posts values (456, 123);
Query OK, 1 row affected (0.00 sec)

mysql> insert into comments values (789, 456);
Query OK, 1 row affected (0.00 sec)

mysql> select * from users;
+-----+
| id  |
+-----+
| 123 |
+-----+
1 row in set (0.00 sec)

mysql> select * from posts;
+-----+--------+
| id  | userid |
+-----+--------+
| 456 |    123 |
+-----+--------+
1 row in set (0.00 sec)

mysql> select * from comments;
+-----+--------+
| id  | postid |
+-----+--------+
| 789 |    456 |
+-----+--------+

现在我们尝试删除,它应该级联到其他表:

mysql> delete from users;
Query OK, 1 row affected (0.03 sec)

mysql> select * from posts;
Empty set (0.00 sec)

mysql> select * from comments;
Empty set (0.00 sec)