Kan*_*thy 2 postgresql upsert postgresql-9.5
我们有一个UPSERT功能通过on conflict do set
. 如何在 set 语句中有条件地设置值,例如
if(excluded.col1 is null) col1=table.col1 else col1=excluded.col1
Run Code Online (Sandbox Code Playgroud)
我们使用的是 Postgres 9.5。
...
SET col1 = COALESCE(excluded.col1, table.col1)
...
Run Code Online (Sandbox Code Playgroud)
当然,两个表都必须可见。
如果您正在更新table1
并且这是唯一的更改,那么使用WHERE
子句会更有效率:
...
SET col1 = excluded.col1
WHERE excluded.col1 IS NOT NULL
AND excluded.col1 IS DISTINCT FROM table1.col1 -- to avoid empty updates
...
Run Code Online (Sandbox Code Playgroud)
关于添加的第二个条件: