truncate foreign key constrained table

本文详细介绍了在MySQL数据库中执行TRUNCATE命令时遇到外键约束冲突的解决方案,包括如何使用设置FOREIGN_KEY_CHECKS为0,先清空相关表的数据,再进行TRUNCATE操作,最后恢复FOREIGN_KEY_CHECKS的默认值。通过实例演示,帮助开发者理解和解决此类常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

执行truncate的时候出现错误

[SQL]
TRUNCATE table person;
[Err] 1701 - Cannot truncate a table referenced in a foreign key constraint (`treasurewinner`.`game_spin_log`, CONSTRAINT `game_spin_log_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `treasurewinner`.`person` (`id`))

因为game_spin_log表有对person表的引用。所以失败了。

搜索答案如下:[url]http://stackoverflow.com/questions/5452760/truncate-foreign-key-constrained-table[/url]
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE table1;
TRUNCATE table2;
SET FOREIGN_KEY_CHECKS=1;
这个FOREIGN_KEY_CHECKS是每次连接设置的,断开连接后会自动恢复成默认值


do we have to set SET FOREIGN_KEY_CHECKS=1; again afterwards? – makeramen Apr 9 at 21:29
I think you have to set it to 1 again, 'cause that is the default value. – PachinSV May 4 at 16:45
2
No, you don't. The setting is only valid during the connection. As soon as you disconnect, the next connection will have it set back to 1. – Pelle ten Cate Jun 27 at 8:07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值