简体   繁体   中英

Drop parent table in MySQL

I've created two simple tables to ilustrate this question.

CREATE TABLE `child` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `father_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_22B354292055B9A2` (`father_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

CREATE TABLE `father` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

ALTER TABLE `child`
  ADD CONSTRAINT `child_ibfk_1` FOREIGN KEY (`father_id`) REFERENCES `father` (`id`) 
  ON DELETE CASCADE;

Imagine that there are rows in the child table linked to the father table through the foreign key.

If I delete a row in the father table that has rows linked to it in the child table, I can delete it anyway because I have "ON DELETE CASCADE" activated.

The problem is that if I try to drop the father table, even if there are no rows neither on the father table nor on the child table, I get the following error message (in phpmyadmin):

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

I tried this command:

SET foreign_key_checks = 0;

But the same error message appears.

I could delete the whole database and create it again, but I don't want to do that if there is another solution (like ON DELETE CASCADE for the rows).

Any suggestions?

Try dropping the constraint itself. alter table child drop foreign key child_ibfk_1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM