【发布时间】:2015-12-23 05:22:46
【问题描述】:
模拟 UPSERT 之前已经是 discusssed。不过,在我的情况下,我有 PRIMARY KEY 和额外的 UNIQUE 约束,并且我想要关于主键的 upsert 语义 - 如果存在则替换现有行,同时检查唯一约束。
这是使用插入或替换的尝试:
drop table if exists test;
create table test (id INTEGER, name TEXT, s INTEGER,
PRIMARY KEY (id, s),
UNIQUE (name, s));
insert or replace into test values (1, "a", 0);
insert or replace into test values (1, "a", 0);
insert or replace into test values (2, "b", 0);
insert or replace into test values (2, "a", 0);
最后一条语句替换了两行。这是“插入或替换”的记录行为,但不是我想要的。
这是“冲突替换”的尝试:
drop table if exists test;
create table test (id INTEGER, name TEXT, s INTEGER,
PRIMARY KEY (id, s) on conflict replace,
UNIQUE (name, s));
insert into test values (1, "a", 0);
insert into test values (1, "a", 0);
我立即收到“UNIQUE 约束失败”。如果不在主键和唯一约束之间共享列,问题就会消失:
drop table if exists test;
create table test (id INTEGER, name TEXT,
PRIMARY KEY (id) on conflict replace,
UNIQUE (name));
insert into test values (1, "a");
insert into test values (1, "a");
insert into test values (2, "b");
insert into test values (2, "a");
在这里,我在最后一个语句中遇到了约束违规,这完全正确。遗憾的是,我确实需要在约束之间共享一列。
这是我对 SQL 或 SQLite 问题的不理解吗?除了首先尝试插入然后在失败时进行更新之外,我如何获得预期的效果?
【问题讨论】: