Bogus foreign key constraint fail

前端 未结 9 1211
南笙
南笙 2020-11-28 01:52

I get this error message:

ERROR 1217 (23000) at line 40: Cannot delete or update a parent row: a foreign key constraint fails

<
相关标签:
9条回答
  • 2020-11-28 02:16

    Disable foreign key checking

    SET FOREIGN_KEY_CHECKS=0
    
    0 讨论(0)
  • 2020-11-28 02:17

    from this blog:

    You can temporarily disable foreign key checks:

    SET FOREIGN_KEY_CHECKS=0;
    

    Just be sure to restore them once you’re done messing around:

    SET FOREIGN_KEY_CHECKS=1;
    
    0 讨论(0)
  • 2020-11-28 02:23

    On demand, now as an answer...

    When using MySQL Query Browser or phpMyAdmin, it appears that a new connection is opened for each query (bugs.mysql.com/bug.php?id=8280), making it neccessary to write all the drop statements in one query, eg.

    SET FOREIGN_KEY_CHECKS=0; 
    DROP TABLE my_first_table_to_drop; 
    DROP TABLE my_second_table_to_drop; 
    SET FOREIGN_KEY_CHECKS=1; 
    

    Where the SET FOREIGN_KEY_CHECKS=1 serves as an extra security measure...

    0 讨论(0)
  • 2020-11-28 02:23

    Cannot delete or update a parent row: a foreign key constraint fails (table1.user_role, CONSTRAINT FK143BF46A8dsfsfds@#5A6BD60 FOREIGN KEY (user_id) REFERENCES user (id))

    What i did in two simple steps . first i delete the child row in child table like

    mysql> delete from table2 where role_id = 2 && user_id =20;

    Query OK, 1 row affected (0.10 sec)

    and second step as deleting the parent

    delete from table1 where id = 20;

    Query OK, 1 row affected (0.12 sec)

    By this i solve the Problem which means Delete Child then Delete parent

    i Hope You got it. :)

    0 讨论(0)
  • 2020-11-28 02:25

    Maybe you received an error when working with this table before. You can rename the table and try to remove it again.

    ALTER TABLE `area` RENAME TO `area2`;
    DROP TABLE IF EXISTS `area2`;
    
    0 讨论(0)
  • 2020-11-28 02:31

    On Rails, one can do the following using the rails console:

    connection = ActiveRecord::Base.connection
    connection.execute("SET FOREIGN_KEY_CHECKS=0;")
    
    0 讨论(0)
提交回复
热议问题