是否可以忽略使用sqlite插入时的外键冲突?
以下是我拥有的两个表的匿名表示:是否可以忽略使用sqlite插入时的外键冲突?,sqlite,foreign-keys,constraints,exists,constraintviolationexception,Sqlite,Foreign Keys,Constraints,Exists,Constraintviolationexception,以下是我拥有的两个表的匿名表示: create table if not exists master_node ( book_name text primary key on conflict ignore not null ); create table if not exists category_table ( book_name text not null, category text not null, foreign key(book_name) r
create table if not exists master_node (
book_name text primary key on conflict ignore not null
);
create table if not exists category_table (
book_name text not null,
category text not null,
foreign key(book_name) references master_node(book_name) on delete cascade,
unique(book_name, category) on conflict ignore
);
在表中插入代码时:
insert into master_node
(book_name)
values
('Harry Potter'),
('Foundation'),
('The Catcher in the Rye')
及
由于约束冲突(外键约束失败)错误,我得到一个[SQLITE\u CONSTRAINT]中止,事务被回滚
我希望通过使用insert或ignore
我能够简单地跳过违反外键约束的行。我还没能找到一种方法来获得这种行为。sqlite提供了这样做的方法吗?没有类似于插入或忽略的方法,它只适用于违反唯一约束和外键约束。
作为一种解决方法,您可以在插入中使用EXISTS
。。。选择
语句:
WITH cte(book_name, category) AS (
VALUES
('Harry Potter', 'Fiction'),
('Harry Potter', 'Fantasy'),
('Foundation', 'Fiction'),
('Foundation', 'Science Fiction'),
('The Catcher in the Rye', 'Coming-of-age'),
('Moby Dick', 'Adventure')
)
INSERT INTO category_table (book_name, category)
SELECT c.book_name, c.category
FROM cte c
WHERE EXISTS (SELECT 1 FROM master_node m WHERE m.book_name = c.book_name)
请参阅。
结果:
如果要违反外键约束,那么使用外键约束有什么意义?如果要添加主节点中不存在的记录,请删除约束。insert或ignore
只忽略唯一的约束冲突。@Ivar我希望FK约束阻止我添加违反约束的行。我只想要从主节点中具有图书名称的行,但是如果我正在进行批量插入,并且有违反约束的行,我只想忽略这些行,而不是回滚整个插入。@forpas是的,我注意到它只在unique
和check
上起作用,我只是在寻找相同的功能,但寻找外键约束。这是否回答了您的问题?谢谢我希望能够使用FKs,因为我需要它们进行级联删除,但是这个解决方案看起来是解决我的问题的最干净的方法。
WITH cte(book_name, category) AS (
VALUES
('Harry Potter', 'Fiction'),
('Harry Potter', 'Fantasy'),
('Foundation', 'Fiction'),
('Foundation', 'Science Fiction'),
('The Catcher in the Rye', 'Coming-of-age'),
('Moby Dick', 'Adventure')
)
INSERT INTO category_table (book_name, category)
SELECT c.book_name, c.category
FROM cte c
WHERE EXISTS (SELECT 1 FROM master_node m WHERE m.book_name = c.book_name)
> book_name | category
> :--------------------- | :--------------
> Harry Potter | Fiction
> Harry Potter | Fantasy
> Foundation | Fiction
> Foundation | Science Fiction
> The Catcher in the Rye | Coming-of-age