我有一个包含两列的表:id,年龄,其中 id 是主键
我知道如何为新的主键插入一个新行,否则如果使用以下 sql 年龄值不为空,则使用新值更新年龄:
insert into obj (id, age)
values (2, 42)
on conflict (id) do
update set age = coalesce(42, obj.age)
但是我该如何处理多行呢?例如:
insert into obj (id, age)
values (2, 42), (3, 43), (5, 60)
on conflict (id) do
update set age = coalesce(???, obj.age)
问题是我应该在 '???' 中输入什么?在合并?
我以为有人建议使用 COALESCE(values(age), obj.age,
我试过了,但没有用(语法错误)。
最佳答案
insert into obj (id, age)
values (2, 42), (3, 43), (5, 60)
on conflict (id) do
update set age = coalesce(excluded.age, obj.age)
注意特殊记录excluded
的使用。每the documentation:
The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table's name (or an alias), and to rows proposed for insertion using the special excluded table.
关于如果不存在,则 SQL 插入多行,否则使用 COALESCE 更新特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50009613/