Cannot drop a mysql table

wesleywmd picture wesleywmd · Feb 3, 2014 · Viewed 17.6k times · Source

I am getting a weird error. I have a table animals, that I am trying to drop. I cannot drop the table because of a foreign key constraint fails. I know that I must drop the foreign keys before I drop the table. The problem is this table has no foreign keys. I have already dropped them. SQLyog reflects that they have been dropped. But I can still find them in the info schema. It as if I drop the key half way or something.

How can I drop this table without dropping the database? I need to rekey this table and I just want to drop it and recreate it.

EDIT: Here is the error message from SQL:

Cannot delete or update a parent row: a foreign key constraint fails

Answer

Bill Karwin picture Bill Karwin · Feb 3, 2014

It doesn't matter if your table animals has foreign keys or not. You would be able to drop the table anyway if it had foreign keys.

What matters is that there are other tables with foreign keys referencing animals.

Here's how you can check:

SELECT TABLE_SCHEMA, TABLE_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE (REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME) = ('mydatabase', 'animals');

Re your comment:

I've never heard of a case where foreign keys were invisible but still preventing the table from being dropped. But I suppose it's possible.

You can drop your table if you do it this way:

mysql> SET FOREIGN_KEY_CHECKS=0;
mysql> DROP TABLE animals;
mysql> SET FOREIGN_KEY_CHECKS=1;

However, I can't predict what may go wrong if the InnoDB tablespace is in a weird state already.

Ultimately, what you may have to do to clean this up is to dump all your InnoDB tables using mysqldump, then shut down the MySQL daemon, remove the InnoDB tablespace files, and then restart and reimport your dumped data. That will eliminate any possibility of tablespace corruption.