MySQL多删除2个表中的Might相互引用的行
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了MySQL多删除2个表中的Might相互引用的行,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2774字,纯文字阅读大概需要4分钟。
内容图文
我有2个MySQL表,其中(InnoDB)外键相互进入.例如,
-- Adminer 4.2.3 MySQL dump
SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`null_or_b_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `null_or_b_id` (`null_or_b_id`),
CONSTRAINT `a_ibfk_1` FOREIGN KEY (`null_or_b_id`) REFERENCES `b` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `a` (`id`, `null_or_b_id`) VALUES
(1, NULL),
(2, 2),
(4, 3),
(3, 4),
(5, 5),
(6, 6),
(7, 7),
(8, 8);
DROP TABLE IF EXISTS `b`;
CREATE TABLE `b` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`null_or_a_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `null_or_a_id` (`null_or_a_id`),
CONSTRAINT `b_ibfk_1` FOREIGN KEY (`null_or_a_id`) REFERENCES `a` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `b` (`id`, `null_or_a_id`) VALUES
(1, NULL),
(8, NULL),
(2, 2),
(4, 3),
(3, 4),
(5, 6),
(6, 7),
(7, 8);
-- 2016-02-03 06:45:07
我想要做的是从a中删除带有id 1,2,3和5的记录,并删除由于外键约束而需要在a和b中删除的所有记录.我试过了:
delete from a where a.id in (1,2,3,5);
delete a,b from a left join b on b.null_or_a_id = a.id where a.id in (1,2,3,5);
以上两者都给出了同样的错误:
Error in query (1451): Cannot delete or update a parent row: a foreign key constraint fails (`test/multi_delete_with_references`.`b`, CONSTRAINT `b_ibfk_1` FOREIGN KEY (`null_or_a_id`) REFERENCES `a` (`id`))
即使我删除了在a中定义的b上的外键约束,我也会得到相同的错误.
我不能做的事情:
>禁用外键检查:因为这两个表也被其他表引用,我不希望这些表有孤立的行,如果这个删除会导致这样的孤立行,我需要删除这个删除失败.
>首先从子表中删除:因为正如您在两个表中都可以看到id为2的行的情况,它们相互引用,因此在没有另一个表的情况下不能删除它们,对于具有ID 3的行也是如此两个表中都有4个,它们构成了一个自引用链.
我已经查看了答案here并且它对我不起作用,因为两个表都相互引用.
有没有办法解决这个问题?
顺便说一下,我还尝试动态生成复杂的嵌套查询,但结果却是无穷无尽的:
delete from a where id in (1,2,3,5);
delete from b where null_or_a_id is not null and null_or_a_id in (select * from (select id from a where id in (1,2,3,5)) x);
delete from a where null_or_b_id is not null and null_or_b_id in (select * from (select id from b where null_or_a_id is not null and null_or_a_id in (select * from (select id from a where id in (1,2,3,5)) x)) x);
delete from b where null_or_a_id is not null and null_or_a_id in (select * from (select id from a where null_or_b_id is not null and null_or_b_id in (select * from (select id from b where null_or_a_id is not null and null_or_a_id in (select * from (select id from a where id in (1,2,3,5)) x)) x)) x)
...
解决方法:
您的问题非常类似于this one并且same solution适用:首先通过将要删除的行中的引用列设置为NULL来删除引用.然后删除.
内容总结
以上是互联网集市为您收集整理的MySQL多删除2个表中的Might相互引用的行全部内容,希望文章能够帮你解决MySQL多删除2个表中的Might相互引用的行所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。