本文介绍了如何截断外键约束表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 mygroup
上的 TRUNCATE 不起作用?
即使我有 ON DELETE CASCADE SET
我得到:
drop database mytest;
创建数据库mytest;
使用mytest;
CREATE TABLE mygroup(
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
)ENGINE = InnoDB;
CREATE TABLE实例(
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
GroupID INT NOT NULL,
DateTime DATETIME DEFAULT NULL,
FOREIGN KEY(GroupID)REFERENCES mygroup(ID)ON DELETE CASCADE,
UNIQUE(GroupID)
)ENGINE = InnoDB;
解决方案
不能 TRUNCATE
应用了FK约束的表( TRUNCATE
与 DELETE
不一样)。
要解决此问题,请使用这些解决方案之一。两者都存在破坏数据完整性的风险。
选项1:
- 删除约束
- 执行
TRUNCATE
现在引用无处 - 创建约束
- Remove constraints
- Perform
TRUNCATE
- Delete manually the rows that now have references to nowhere
- Create constraints
$ b 选项2: user447951 在中建议 em>
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE表$ table_name;
SET FOREIGN_KEY_CHECKS = 1;
Why doesn't a TRUNCATE on mygroup
work?Even though I have ON DELETE CASCADE SET
I get:
drop database mytest;
create database mytest;
use mytest;
CREATE TABLE mygroup (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
) ENGINE=InnoDB;
CREATE TABLE instance (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
GroupID INT NOT NULL,
DateTime DATETIME DEFAULT NULL,
FOREIGN KEY (GroupID) REFERENCES mygroup(ID) ON DELETE CASCADE,
UNIQUE(GroupID)
) ENGINE=InnoDB;
解决方案
You cannot TRUNCATE
a table that has FK constraints applied on it (TRUNCATE
is not the same as DELETE
).
To work around this, use either of these solutions. Both present risks of damaging the data integrity.
Option 1:
Option 2: suggested by user447951 in their answer
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table $table_name;
SET FOREIGN_KEY_CHECKS = 1;
这篇关于如何截断外键约束表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!