简体   繁体   English

使用外键约束从MySQL表中删除

[英]Deleting from a MySQL table with foreign key constraints

I have two tables, with some data loaded in it and the two reference each other. 我有两个表,其中加载了一些数据,两个表互相引用。 Table B references the primary key of Table A. I manually attempt to delete some table rows from Table A that are present in Table B, and I get this: 表B引用了表A的主键。我手动尝试从表A中删除表A中存在的一些表行,我得到:

#1451 - Cannot delete or update a parent row: a foreign key constraint fails ( TableA . TableB , CONSTRAINT TableB_ibfk_2 FOREIGN KEY ( column ) REFERENCES flashcard ( primaryKeyColumn )) #1451 -无法删除或更新父行,外键约束失败( TableATableB ,约束TableB_ibfk_2外键( column )参考flashcardprimaryKeyColumn ))

I am not quite sure what's up here. 我不太确定这里有什么。 From what I understand,if I delete some rows of TableA then they should automatically also delete the corresponding rows present in Table B (ie if they are present in Table B) but clearly this isn't the case here and it's prompting the above error. 根据我的理解,如果我删除TableA的某些行,那么它们应该自动删除表B中存在的相应行(即如果它们存在于表B中)但显然这不是这里的情况并且它提示上述错误。

Anybody wanna whack the side of my head and let me know why ? 有人想打我的脑袋让我知道为什么吗?

Unfortunately, the automatic deletion that you think should happen does not happen. 不幸的是,您认为应该发生的自动删除不会发生。 You would need to manually delete the rows in Table B that contain the ID from the row in Table A that you wish to remove. 您需要手动删除表B中包含您要删除的表A中的行的ID的行。

Try adding ON DELETE CASCADE to your foreign key column definition in Table B. 尝试将ON DELETE CASCADE添加到表B中的外键列定义中。

If you are using Hibernate, or some other ORM tool, it would have a "cascade" mechanism that would handle this automatically. 如果您正在使用Hibernate或其他一些ORM工具,它将具有一个“级联”机制,可以自动处理这个问题。 But here since you are interfacing with the database directly, you must keep in mind that a row cannot be deleted if the ID of said row exists in any other table as a foreign key (as in your case, the primary key of A exists in some of the rows in B). 但是,由于您直接与数据库连接,因此必须记住,如果所述行的ID作为外键存在于任何其他表中,则无法删除行(在您的情况下,A的主键存在于B)中的一些行。 Unless of course you specify the ON DELETE CASCADE property. 除非您指定ON DELETE CASCADE属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM