错误145123000-MySQL触发器中的触发器错误

问题描述

    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,'bbb','2011-9-1',1),-> (20,'ddd','2012-8-2',2),-> (30,'fff','2013-7-3',3),-> (40,'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上有一个删除触发器,在该触发器中,您从同一表中删除,该表调用了另一个触发器,依此类推。

数据库不允许这样做,并返回该错误消息。