使用sqlite插入时是否可以忽略外键冲突?

问题描述

这是我拥有的两个表的匿名表示:

CREATE VIEW v_numbers AS 
SELECT n.*,CASE WHEN a <> 0 
        THEN (b / c) - avg(b / c) FILTER(WHERE a <> 0) OVER (PARTITION BY user)
    END AS e 
FROM numbers n

当我在表格中插入代码时:

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')

我收到一个 insert or ignore into category_table (book_name,category) values (Harry Potter','Fiction'),('Harry Potter','Fantasy'),('Foundation','Science Fiction'),('The Catcher in the Rye','Coming-of-age'),('Moby Dick','Adventure') 错误并且事务被回滚。

我希望通过使用 [SQLITE_CONSTRAINT] Abort due to constraint violation (FOREIGN KEY constraint failed) 我能够简单地跳过具有外键约束违规的行。我一直无法找到获得这种行为的方法。 sqlite 是否提供了这样做的方法?

解决方法

没有等效的 INSERT OR IGNORE,它仅适用于违反 UNIQUE 约束和违反 FOREIGN KEY 约束。

作为一种解决方法,您可以在 EXISTS 语句中使用 INSERT ... SELECT

WITH cte(book_name,category) AS (
    VALUES 
    ('Harry Potter','Fiction'),('Harry Potter','Fantasy'),('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)

参见demo
结果:

> book_name              | category       
> :--------------------- | :--------------
> Harry Potter           | Fiction        
> Harry Potter           | Fantasy        
> Foundation             | Fiction        
> Foundation             | Science Fiction
> The Catcher in the Rye | Coming-of-age 

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...