[英]Error 1451 (23000) - Trigger Error in MySQL trigger
mysql> create database lib;
Query OK, 1 row affected (0.31 sec)
mysql> use lib;
Database changed
mysql> create table library_2
-> (id int AUTO_INCREMENT primary key,
-> Book_name varchar(20),
-> Details varchar(50));
Query OK, 0 rows affected (2.24 sec)
mysql> insert into library_2 values
-> (1,'aaa','bbb'),
-> (2,'ccc','ddd'),
-> (3,'eee','fff'),
-> (4,'ggg','hhh');
Query OK, 4 rows affected (0.46 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select*from library_2;
+----+-----------+-------------------+
| id | Book_name | Details |
+----+-----------+-------------------+
| 1 | aaa | bbb |
| 2 | ccc | ddd |
| 3 | eee | fff |
| 4 | ggg | hhh |
+----+-----------+-------------------+
4 rows in set (0.00 sec)
mysql> create table library_audit2
-> (id int AUTO_INCREMENT primary key,
-> Book_Name varchar(20) not null,
-> Details varchar(50) default null,
-> change_date date,
-> library_id int,
-> foreign key(library_id) REFERENCES library_2(id));
Query OK, 0 rows affected (2.33 sec)
mysql> insert into library_audit2 values
-> (10,'aaa','bbb','2011-9-1',1),
-> (20,'ccc','ddd','2012-8-2',2),
-> (30,'eee','fff','2013-7-3',3),
-> (40,'ggg','hhh','2014-6-4',4);
Query OK, 4 rows affected (0.20 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select*from library_audit2;
+----+-----------+---------+-------------+------------+
| id | Book_Name | Details | change_date | library_id |
+----+-----------+---------+-------------+------------+
| 10 | aaa | bbb | 2011-09-01 | 1 |
| 20 | ccc | ddd | 2012-08-02 | 2 |
| 30 | eee | fff | 2013-07-03 | 3 |
| 40 | ggg | hhh | 2014-06-04 | 4 |
+----+-----------+---------+-------------+------------+
4 rows in set (0.00 sec)
mysql> create trigger BeforeLibraryDelete1
-> BEFORE DELETE
-> ON library_audit2 FOR EACH ROW
-> BEGIN
-> declare id1 int;
-> select library_id into id1 from library_audit2 where change_date=OLD.change_date;
-> delete from library_2 li where li.id=id1;
-> END $$
Query OK, 0 rows affected (0.45 sec)
mysql> DELIMITER ;
mysql> Delete from library_audit2 where change_date='2011-09-01';
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`abc`.`library_audit2`, CONSTRAINT `library_audit2_ibfk_1` FOREIGN KEY (`library_id`) REFERENCES `library_2` (`id`))
我知道這個錯誤意味着什么,但我需要一個不同的觸發器查詢來糾正這個問題。 無論我嘗試什么,這似乎都以錯誤告終。 請向我提供一個有效的查詢。 也因為 MYSQL 不能與 INSTEAD OF 一起使用,所以不要向我提供包含 INSTEAD OF DELETE 的查詢。 但是在 MYSQL 中替換它會受到高度贊賞。
你在無限循環中運行。
您在表library_audit2
上有一個刪除觸發器,在該觸發器中,您從調用另一個觸發器的同一個表中刪除,依此類推。
DB 不允許這樣做並返回該錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.