Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop tables with cyclic foreign keys in MySQL

I have two tables, Parent and Child. The column Parent.favorite_child has a foreign key constraint pointing to Child.id. And the column Child.parent has a foreign key constraint pointing to Parent.id.

Now here's the weird part. I'm trying to drop my Child table, which contains no records, but MySQL is giving me the error:

ERROR 1217: Cannot delete or update a parent row: a foreign key constraint fails
SQL Statement:
drop table `mydatabase`.`Child`

Why is MySQL throwing this error? There are literally no records in the Child table with which anything could be pointing to or from.

like image 371
Cerin Avatar asked Oct 25 '25 03:10

Cerin


1 Answers

You need to first drop the foreign key on the parent table before you can delete the child table:

ALTER TABLE `Parent` DROP FOREIGN KEY `Parent_ibfk_1` ;
like image 57
ghbarratt Avatar answered Oct 27 '25 16:10

ghbarratt