删除 MySQL 中的父表

发布于 2024-11-15 04:44:04 字数 997 浏览 3 评论 0原文

我创建了两个简单的表格来说明这个问题。

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;

想象一下,子表中有一些行通过外键链接到父表。

如果我删除父表中的一行,而该行在子表中具有链接到它的行,则无论如何我都可以删除它,因为我激活了“ON DELETE CASCADE”。

问题是,如果我尝试删除父表,即使父表和子表上都没有行,我也会收到以下错误消息(在 phpmyadmin 中):

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

我尝试了此命令:

SET foreign_key_checks = 0;

但同样的错误出现消息。

我可以删除整个数据库并再次创建它,但如果有其他解决方案(例如行的 ON DELETE CASCADE),我不想这样做。

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

糖果控 2024-11-22 04:44:04

尝试删除约束本身。更改表子级删除外键child_ibfk_1;

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文