sql - 在事务期间更新从属表时,“FOREIGN KEY约束失败”

标签 sql sqlite

我有三个具有链依赖关系的表,如下所示:

pragma foreign_keys = ON;
create table foo (id integer primary key);
create table bar (id integer primary key references foo(id));
create table baz (id integer primary key references bar(id));
insert into foo values (1), (2);
insert into bar values (1);
insert into baz values (1);


我想更新子表barbaz。但是,在转换中更新它们时,出现错误:

begin;
update bar set id = 2 where id = 1;
update baz set id = 2 where id = 1;
commit;
-- Error: FOREIGN KEY constraint failed


如何同时更新子表以避免外键约束错误?

最佳答案

如果在每个外键上设置ON UPDATE CASCADE,则关系的主键端的更改应传播到外键域。可以这样设置:

create table foo (id integer primary key);
create table bar (id integer primary key references foo(id) on update cascade);
create table baz (id integer primary key references bar(id) on update cascade);


然后,您只需要像这样更新bar.id,更改就会在baz.id中自动发生。

begin;
update bar set id = 2 where id = 1;
commit;

关于sql - 在事务期间更新从属表时,“FOREIGN KEY约束失败”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58125204/

相关文章:

sql - 使用 join 进行高级 sql 查询

c# - 连接到 Always On 可用性组的只读实例

Android - 在本地存储大量数据,xml/json 或 SQLite?

sql - PostgreSQL 按 Windows CompareStringA 排序

SQLite 从基于其他表的表中选择

php - 多个结果正在上传到表中

sql - Android SQLite :Unable to solve syntax error in query

java - 如何缓存游标对象?

c++ - qt c++ 中的 Qsqlite 重复连接警告

java - JDBC Sqlite 尝试获取可空列