如果不存在,则 SQL 插入多行,否则使用 COALESCE 更新特定列

标签 sql postgresql unique upsert

我有一个包含两列的表: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/

相关文章:

mysql - 通过保留表中的最小行来删除重复记录

c# - .NET:在数据库字段中允许 NULLS?

sql - 如何在 PostgreSQL 中创建临时函数?

Django 查询返回空值

python - 从 href 属性 Python 创建一个带有漂亮汤的独特列表

sql - 窗口函数/聚合函数/中断窗口

c# - 无法使用 Dapper 获取 Long 类型的数据

sql-server - SQL 服务器 2008 : Unique constraint for values non-related with columns

ruby-on-rails - PostgreSQL:按多个列权重排序

xslt - 如果 parent 没有匹配的 child ,则选择XSLT选择节点