Tuesday, 13 November 2018

Mysql: Force drop mysql bypassing foreign key constraint

I'm trying to delete all tables from a database except one, and I end up having the 
following error:
Cannot delete or update a parent row: a foreign key constraint fails
Of course I could trial and error to see what those key constraints are and eventually delete 
all tables but I'd like to know if there is a fast way to force drop all tables (as I'll be able 
to re-insert those I don't want deleted).
Google aimed me at some site that suggested the following method:
mysql> SET foreign_key_checks = 0;
mysql> drop table ...
mysql> SET foreign_key_checks = 1;
Short answer is it didn't really do the trick since I ended up receiving the same error while
 I was able to delete some more tables. I've seen on ways to get all foreign keys linked to 
a certain table but that's way too time consuming unless I script it all (which is doable in 
the case there is no other option)
Database is 4.1 so I can't use DROP DATABASE
Ideas?

 Answers





If you are using phpmyadmin then this feature is already there.
  • Select the tables you want to drop
  • From the dropdown at the bottom of tables list, select drop

  • A new page will be opened having checkbox at the bottom saying "Foreign key check", uncheck it.

  • Confirm the deletion by accepting "yes".



Drop database exist in all versions of MySQL. But if you want to keep the table structure, 
here is an idea
mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql
This is a program, not a mysql command
Then, log into mysql and
source dump.sql;

0 comments:

Post a Comment