Deleting a row with a self-referencing foreign key(删除具有自引用外键的行)
问题描述
我有一个 MySQL 表,其定义如下:
<上一页>创建表`留言簿`(`Id` int(10) 无符号非空,`ThreadId` int(10) unsigned NOT NULL,主键(`Id`),KEY `ThreadId` (`ThreadId`),约束`guestbook_ibfk_1`外键(`ThreadId`)参考`guestbook`(`Id`)) 引擎=InnoDB;目前表格中只有 1 行:
<上一页>mysql> 从留言簿中选择 *;+-----+----------+|身份证 |线程 ID |+-----+----------+|211 |211 |+-----+----------+问题是没有办法在不破坏约束的情况下删除这一行.
<上一页>mysql> 从留言簿中删除;错误 1451 (23000):无法删除或更新父行:外键约束失败(`polaris`.`guestbook`, CONSTRAINT`guestbook_ibfk_1` FOREIGN KEY (`ThreadId`) REFERENCES`guestbook` (`Id`))由于 ThreadId 列定义为非空,因此也无法暂时将 ThreadId 设置为不同的值来删除该行.有没有办法在不更改表定义或删除整个表的情况下删除行?
您可以使用此查询暂时禁用外键约束:
SET foreign_key_checks = 0;
I have a MySQL table whose definition is as follows:
CREATE TABLE `guestbook` ( `Id` int(10) unsigned NOT NULL, `ThreadId` int(10) unsigned NOT NULL, PRIMARY KEY (`Id`), KEY `ThreadId` (`ThreadId`), CONSTRAINT `guestbook_ibfk_1` FOREIGN KEY (`ThreadId`) REFERENCES `guestbook` (`Id`) ) ENGINE=InnoDB;
and currently there's only 1 row in the table:
mysql> select * from guestbook; +-----+----------+ | Id | ThreadId | +-----+----------+ | 211 | 211 | +-----+----------+
The problem is that there's no way to delete this row without breaking the constraint.
mysql> delete from guestBook; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`polaris`.`guestbook`, CONSTRAINT `guestbook_ibfk_1` FOREIGN KEY (`ThreadId`) REFERENCES `guestbook` (`Id`))
As the ThreadId column was defined not null, it is also impossible to set the ThreadId to a different value temporarily to delete the row. Is there a way to delete the row without changing the definition of the table or dropping the entire table?
You can temporarily disable foreign key constraints with this query:
SET foreign_key_checks = 0;
这篇关于删除具有自引用外键的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:删除具有自引用外键的行
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01