Deleting from a MySQL table with foreign key constraints(从具有外键约束的 MySQL 表中删除)
问题描述
我有两个表,其中加载了一些数据,并且两个表相互引用.表 B 引用了表 A 的主键.我手动尝试从表 A 中删除表 B 中存在的一些表行,我得到了这个:
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:
#1451 - 无法删除或更新父行:外键约束失败 (TableA
.TableB
, CONSTRAINT TableB_ibfk_2
FOREIGN KEY (column
) REFERENCES flashcard
(primaryKeyColumn
))
#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
))
我不太确定这里发生了什么.据我了解,如果我删除 TableA 的某些行,那么它们也应该自动删除表 B 中存在的相应行(即,如果它们存在于表 B 中)但显然这里不是这种情况,它会提示上述错误.
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 (i.e if they are present in Table B) but clearly this isn't the case here and it's prompting the above error.
有人想敲打我的脑袋告诉我为什么吗?
Anybody wanna whack the side of my head and let me know why ?
推荐答案
很遗憾,您认为应该发生的自动删除并没有发生.您需要手动删除表 B 中包含要删除的表 A 行中的 ID 的行.
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.
尝试将 ON DELETE CASCADE 添加到表 B 中的外键列定义中.
Try adding ON DELETE CASCADE to your foreign key column definition in Table B.
如果您使用的是 Hibernate 或其他一些 ORM 工具,它会有一个级联"机制来自动处理这个问题.但是在这里,由于您直接与数据库交互,因此您必须记住,如果该行的 ID 作为外键存在于任何其他表中,则无法删除该行(如您的情况,A 的主键存在于B)中的一些行.当然,除非您指定 ON DELETE CASCADE 属性.
If you are using Hibernate, or some other ORM tool, it would have a "cascade" mechanism that would handle this automatically. 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). Unless of course you specify the ON DELETE CASCADE property.
这篇关于从具有外键约束的 MySQL 表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从具有外键约束的 MySQL 表中删除
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01