如何在PostgreSQL中使用带有ON CONFLICT子句的IF ELSE语句?

5
我有一个Airflow作业,每天通过INSERT ON CONFLICT语句更新表的列。该表包含一个名为updated_mode的枚举类型字段,当行是由作业插入/更新时,它设置为automatic,如果手动操作,则设置为manual。 现在,我希望我的作业仅在updated_mode设置为automatic时才更新行。我该怎么做?
基本上,我想做以下事情:
Insert into table (data) values (data) on conflict (fields) if updated_mode=automatic set data=excluded.data else do nothing
3个回答

6

3

您应该使用常规的WHERE条件。神奇的EXCLUDEED RECORD将包含现有的冲突记录。大致如此:

 Insert into table (data) values (data) 
 on conflict (fields) do update 
   set data=excluded.data 
 WHERE updated_mode=automatic 
   and fields = EXCLUDEED.fields

我假设fields是冲突字段,表名为data

1
“OLD”是指“排除”吗?我看PG 13不接受在“ON CONFLICT”中使用“OLD”。 - Alex Yu
第二个检查“fields = EXCLUDEED.fields”是多余的。 - Laurenz Albe

1

https://www.postgresql.org/docs/release/14.0/

  • 允许在ON CONFLICT的WHERE子句中使用带表格限定符的列名(Tom Lane)

现在您可以更轻松地引用被排除的列名和原始表格列。
设置表格。

create table test101(id bigint primary key, field1 text, update_mode boolean);
insert into test101 values (1,'a', TRUE);
insert into test101 values (2 ,'b', false);

排除是指您想要插入的部分。

--this one will insert.
insert into  test101(id, field1,update_mode) 
    values(1,'asdf', TRUE)
on conflict (id) 
do update set
field1 = excluded.field1
WHERE 
    excluded.update_mode= test101.update_mode;

--this will not insert
insert into  test101(id, field1,update_mode)
values(2,'asdf', TRUE)
on conflict (id) 
do update set
field1 = excluded.field1
WHERE 
excluded.update_mode= test101.update_mode;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接