狐狸.fox 2013-03-19 14:03 采纳率: 0%
浏览 285

如何在 MySQL 中临时禁用外键约束?

Is it possible to temporarily disable constraints in MySQL?

I have two Django models, each with a ForeignKey to the other one. Deleting instances of a model returns an error because of the ForeignKey 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?

转载于:https://stackoverflow.com/questions/15501673/how-to-temporarily-disable-a-foreign-key-constraint-in-mysql

  • 写回答

10条回答 默认 最新

  • derek5. 2013-03-19 14:33
    关注

    Instead of disabling your constraint, permanently modify it to ON DELETE SET NULL. That will accomplish a similar thing and you wouldn't have to turn key checking on and off. Like so:

    ALTER TABLE tablename1 DROP FOREIGN KEY fk_name1; //get rid of current constraints
    ALTER TABLE tablename2 DROP FOREIGN KEY fk_name2;
    
    ALTER TABLE tablename1 
      ADD FOREIGN KEY (table2_id) 
            REFERENCES table2(id)
            ON DELETE SET NULL  //add back constraint
    
    ALTER TABLE tablename2 
      ADD FOREIGN KEY (table1_id) 
            REFERENCES table1(id)
            ON DELETE SET NULL //add back other constraint
    

    Have a read of this (http://dev.mysql.com/doc/refman/5.5/en/alter-table.html) and this (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html).

    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)