MySQL:删除一行忽略外键约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9912663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL: delete a row ignoring foreign key constraint
提问by Xavier_Ex
so I am working on a few tables and there are some data inconsistency between them... One or two tables have a foreign key constraint on a particular table (call it table X), but that table has multiple rows with the foreign key column.
所以我正在处理几个表,它们之间存在一些数据不一致......一个或两个表在特定表上有外键约束(称为表 X),但该表有多行带有外键列.
What I want to do is to remove the duplicated rows in table X, but the foreign key constraint is preventing me from doing this. Is there a way to force delete the rows while ignoring the foreign key constraint since I know what I'm doing?
我想要做的是删除表 X 中的重复行,但外键约束阻止我这样做。有没有办法在忽略外键约束的同时强制删除行,因为我知道我在做什么?
回答by Matt Dodge
SET foreign_key_checks = 0;
SET foreign_key_checks = 0;
That will prevent MySQL from checking foreign keys. Make sure to set it back to 1 when you are done though.
这将阻止 MySQL 检查外键。但是,请确保在完成后将其设置回 1。
Also, you could always drop the foreign key and then add it later if you wanted to only affect a singular key
此外,如果您只想影响单个键,您可以随时删除外键,然后再添加它
ALTER TABLE tableName DROP FOREIGN KEY fk;
ALTER TABLE tableName DROP FOREIGN KEY fk;