ERROR 1451: 1451: Cannot delete or update a parent row: a foreign key constraint fails
Before deleting the product your trigger will insert into product_audit
. If the product_id
column in product_audit
is a foreign key to product
, then you can't delete this row from product
anymore, because it is a parent to the newly created row in product_audit
.
Try to remove the foreign key constraint from product_audit
.
Since you didn't show the table definition for product_audit
, the above is guessing in that regard. (At the time of writing, that is. But my guess was correct!)
The entry which you're trying to delete
in your product
table is a parent
to some other table. Meaning that, if you try to delete an entry from your product
table where product_id=1
you have to make sure that all the entries refrencing to this entry should be deleted first.
Let's assume you have a table called user
+--------+-------+--------+| UserID | Name | Gender |+--------+-------+--------+| 1 | Jason | Male |+--------+-------+--------+| 2 | Sara | Female |+--------+-------+--------+| 3 | John | Male |+--------+-------+--------+
and you have a table user_address
which is referencing to user
table with user_id
being foreign key.
+-----------+-----------+--------+| AddressID | Address | UserID |+-----------+-----------+--------+| 1 | Address A | 1 |+-----------+-----------+--------+| 2 | Address B | 1 |+-----------+-----------+--------+| 3 | Address C | 2 |+-----------+-----------+--------+
Now if you want to run a delete query on user
like this:
delete from user where userID=1;
You have to make sure to delete all the children (dependencies) to it, which in this game is Address A
and Address B
.
You can check if product_id
is used as FOREIGN KEY
in any other table by running the follwing query.
SELECT constraint_name, table_name FROM information_schema.table_constraints WHERE constraint_type = 'FOREIGN KEY' AND table_schema = DATABASE() AND constraint_name LIKE '%product_id%'ORDER BY constraint_name;`