我在 SQLite 中遇到了 UPSERT 语句的问题。我有一个主库和一个从库,对从库的更新应该合并到主库中。我想使用 UPSERT 子句。这适用于插入values()
但不适用于从子查询插入。
文档(至少是图表)表明它应该有效:https://www.sqlite.org/lang_insert.html
但我收到一个错误。我错过了什么吗?
sqlite> create table orig (id int unique, a int);
sqlite> create table copy (id int unique, a int);
sqlite> insert into orig values (1,0);
sqlite> insert into copy values (1,0);
sqlite> insert into orig values (1,1) on conflict do update set a=1;
sqlite> select * from orig;
1|1
sqlite> insert into orig select * from copy on conflict do update set a=2;
Parse error: near "do": syntax error
insert into orig select * from copy on conflict do update set a=2;
error here ---^
我也尝试过不同的表达方式,但无济于事:
sqlite> insert into orig select * from copy on conflict do nothing;
Parse error: near "do": syntax error
insert into orig select * from copy on conflict do nothing;
error here ---^
sqlite> insert into orig select * from copy on conflict (id) do update set a=2;
Parse error: near "do": syntax error
ert into orig select * from copy on conflict (id) do update set a=2;
error here ---^
sqlite3 --version 3.40.1 2022-12-28
这在UPSERT手册条目的解析歧义部分中进行了解释:
因此,为了解决您的问题,您需要
where true
在更新插入之前添加冗余on
:现场演示