MySQL触发器:ERROR#1442

时间:2015-04-08 10:17:54

标签: mysql mysql-error-1442

我正在研究MySQL数据库并面临问题创建触发器。 在数据库中,假设有两个表," user"和"书"具有1对多的关系,user_id是" book"中的外键。表。我创建了一个触发器来减少" book_count"列"用户"当书被删除时,表格为1。

CREATE TRIGGER `after_book_delete` AFTER DELETE ON `book`
FOR EACH ROW BEGIN
UPDATE `user` SET `user`.book_count = `user`.book_count - 1 WHERE `user`.user_id = OLD.user_id;
END;

现在我想在删除用户时删除用户的所有图书。我试过这个:

CREATE TRIGGER `before_user_delete` BEFORE DELETE ON `user`
FOR EACH ROW BEGIN
DELETE FROM `book` WHERE user_id = OLD.user_id;
END;

这会返回以下错误:

#1442 - Can't update table 'user' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

我可以理解错误是针对第一次尝试更新用户表中即将删除的行的触发器。如果我想通过触发器执行此操作,是否有任何解决方法?

1 个答案:

答案 0 :(得分:2)

使用

user表中向book声明外键约束
 ON DELETE CASCADE ON UPDATE CASCADE

例如,

 CONSTRAINT fk_userbook FOREIGN KEY (id) REFERENCES user (id) ON DELETE CASCADE ON UPDATE CASCADE

然后,如果删除用户,所有相关的书籍也将被删除,从而无需触发。

扩展示例,

create table user (
     id int,
     constraint pk_user primary key(id)
) CHARACTER SET utf8 COLLATE utf8_unicode_ci;

create table book (
     id int,
     uid int,
     bname varchar(10),
     constraint pk_book primary key(id),
     constraint fk_userbook foreign key (uid) references user (id) on update cascade on delete cascade
) CHARACTER SET utf8 COLLATE utf8_unicode_ci;

insert into user values(1);
insert into book values(1,1,"a");
insert into book values(2,1,"b");
insert into book values(3,1,"c");
insert into book values(4,1,"d");

delete from user where user.id = 1;
select * from book;

如您所见,这会自动处理您的触发器试图实现的目标。