MySQL Multi DELETE 如果与外键存在关系
MySQL Multi DELETE If relationship exists with foriegn key
我正在尝试(在单个语句中)删除一行及其所有关系,即使所有这些关系都不存在。级联删除不是选项,我宁愿避免子查询。
以下是由于外键关系而失败的示例:
CREATE TABLE test(id integer, title varchar(100), primary key(id));
INSERT into test(id, title) values(1, "Hello");
CREATE TABLE ref_a(id integer, test_id integer, primary key(id), key(test_id), constraint foreign key(test_id) references test(id));
INSERT into ref_a(id, test_id) values(1, 1);
CREATE TABLE ref_b(id integer, test_id integer, primary key(id), key(test_id), constraint foreign key(test_id) references test(id));
SET GLOBAL FOREIGN_KEY_CHECKS=1;
DELETE test, ref_a, ref_b FROM test
LEFT JOIN ref_a ON ref_a.test_id = test.id
LEFT JOIN ref_b ON ref_b.test_id = test.id
WHERE test.id = 1;
失败并出现错误
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`product`.`ref_a`, CONSTRAINT `ref_a_ibfk_1` FOREIGN KEY (`test_id`) REFERENCES `test` (`id`))
这可以吗?
数据库是InnoDb。 MySql v 5.6.36
对于您的问题,有以下三种选择:
启用ON DELETE CASCADE
。
但这显然不是你的选择
在 运行 查询之前禁用 foreign_key_checks
,然后 re-enable 禁用
运行两个查询;首先删除引用行 (ref_a
, ref_b
),然后删除 test
中的行
否则你这是不可能的,这就是外键的作用;以保证数据的一致性。
我正在尝试(在单个语句中)删除一行及其所有关系,即使所有这些关系都不存在。级联删除不是选项,我宁愿避免子查询。
以下是由于外键关系而失败的示例:
CREATE TABLE test(id integer, title varchar(100), primary key(id));
INSERT into test(id, title) values(1, "Hello");
CREATE TABLE ref_a(id integer, test_id integer, primary key(id), key(test_id), constraint foreign key(test_id) references test(id));
INSERT into ref_a(id, test_id) values(1, 1);
CREATE TABLE ref_b(id integer, test_id integer, primary key(id), key(test_id), constraint foreign key(test_id) references test(id));
SET GLOBAL FOREIGN_KEY_CHECKS=1;
DELETE test, ref_a, ref_b FROM test
LEFT JOIN ref_a ON ref_a.test_id = test.id
LEFT JOIN ref_b ON ref_b.test_id = test.id
WHERE test.id = 1;
失败并出现错误
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`product`.`ref_a`, CONSTRAINT `ref_a_ibfk_1` FOREIGN KEY (`test_id`) REFERENCES `test` (`id`))
这可以吗?
数据库是InnoDb。 MySql v 5.6.36
对于您的问题,有以下三种选择:
启用
ON DELETE CASCADE
。 但这显然不是你的选择在 运行 查询之前禁用
foreign_key_checks
,然后 re-enable 禁用运行两个查询;首先删除引用行 (
ref_a
,ref_b
),然后删除test
中的行
否则你这是不可能的,这就是外键的作用;以保证数据的一致性。