[英]Cannot truncate a table referenced in a foreign key constraint
Cannot truncate a table referenced in a foreign key constraint.无法截断外键约束中引用的表。 What should i do first to enable truncate?我应该先做什么才能启用截断?
details:细节:
(
`guacamole`.`guacamole_connection_history`,
CONSTRAINT `guacamole_connection_history_ibfk_2`
FOREIGN KEY (`connection_id`)
REFERENCES `guacamole`.`guacamole_connection` (`connection_id`)
)
I want to clear guacamole_connection table for development testing.我想清除 guacamole_connection 表以进行开发测试。
You can do truncate by skipping foreign key checks.您可以通过跳过外键检查来进行截断。
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table1;
SET FOREIGN_KEY_CHECKS = 1;
TRUNCATE it's not equivalent to DELETE: TRUNCATE it's DDL operations while DELETE is a DML operation. TRUNCATE 它不等同于 DELETE:TRUNCATE 它是 DDL 操作,而 DELETE 是 DML 操作。 In other words TRUNCATE alter the table structure (ie freeing storage and modifying other properties depending on RDBMS you are working on) while DELETE just modify the data on in performing every validation that your model has specified (ie foreing key constraints, check constraints, etc.)换句话说,TRUNCATE 会改变表结构(即根据您正在处理的 RDBMS 释放存储空间并修改其他属性),而 DELETE 只是在执行模型指定的每个验证时修改数据(即前键约束、检查约束等) .)
Why would you want to truncate the table?为什么要截断表格? Well, it's faster as it doesn't has to run any validation (that's why your FK are affecting the truncate operation), and allows you to free all the space the table (and it's index) is currently allocating.嗯,它更快,因为它不必运行任何验证(这就是为什么您的 FK 会影响截断操作),并允许您释放表(及其索引)当前分配的所有空间。
So, if you want to truncate your table you should:所以,如果你想截断你的表,你应该:
Internally the operation use to be (again depending on the RDBMS) equivalent to DROP and CREATE the FKs.在内部,操作使用(再次取决于 RDBMS)相当于 DROP 和 CREATE FK。 The difference usually is related to the permissions needed as conceptually it's not the same to create/delete a FK than enable/disable it差异通常与所需的权限有关,因为从概念上讲,创建/删除 FK 与启用/禁用它不同
Why not add a constraint adding ON DELETE CASCADE
and ON UPDATE CASCADE
?为什么不添加一个约束添加ON DELETE CASCADE
和ON UPDATE CASCADE
? Then all you need to do is TRUNCATE guacamole_connection CASCADE
然后你需要做的就是TRUNCATE guacamole_connection CASCADE
Example:例子:
ALTER TABLE
guacamole_connection_history
ADD CONSTRAINT
guacamole_connection_history_cascade_delete
FOREIGN KEY (connection_id)
REFERENCES guacamole_connection (connection_id)
ON UPDATE CASCADE ON DELETE CASCADE;
Then just run TRUNCATE guacamole_connection CASCADE
然后只需运行TRUNCATE guacamole_connection CASCADE
Be sure to remove entries from any dependent tables first.确保首先从任何依赖表中删除条目。 For example:例如:
TRUNCATE TABLE guacamole_connection_history;
TRUNCATE TABLE guacamole_connection;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.