如何在MySQL中临时禁用外键约束? [英] How can I temporarily disable a foreign key constraint in MySQL?

查看:293
本文介绍了如何在MySQL中临时禁用外键约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在MySQL中暂时禁用约束?

Is it possible to temporarily disable constraints in MySQL?

我有两个Django模型,每个模型都有一个到另一个的外键.由于外键约束,删除模型实例将返回错误:

I have two Django models, each with a foreign key to the other one. Deleting instances of a model returns an error because of the foreign key constraint:

cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)
transaction.commit_unless_managed()  #a foreign key constraint fails here

cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)
transaction.commit_unless_managed()

是否可以暂时禁用约束并仍然删除?

Is it possible to temporarily disable constraints and delete anyway?

推荐答案

尝试DISABLE KEYS

SET FOREIGN_KEY_CHECKS=0;

请确保

SET FOREIGN_KEY_CHECKS=1;

之后.

这篇关于如何在MySQL中临时禁用外键约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆