Postgres ON CONFLICT DO 仅更新 python 中的非空值

2024-01-14

我有一个表,在处理记录时,我要么获得完整记录,要么只获得要更新的列。

我想编写一个查询来处理更新,但只更新具有非空值的列。例如,

现有表:

1 | John Doe | USA
2 | Jane Doe | UK

传入记录:

(3, Kate Bill, Canada)
(2, null, USA)

我想插入第一条记录,并且在第二条记录上的键冲突时仅更新最后一列。

我不知道如何使用execute_values 方法调用来编写此代码:

execute_values(cursor, "INSERT INTO user_data\
           (id, name, country) VALUES %s ON CONFLICT DO UPDATE SET \
            <how to only set non null values here>", vendor_records)

我正在使用 psycopg2 来执行此操作。


In the 关于冲突 https://www.postgresql.org/docs/current/sql-insert.html(特别注意更新集合名称=表达式)您可以使用合并与排除的值将列更新为指定值(如果不为空)或现有值(如果指定为空); 这将是这样的格式:

-- setup  
 create table test1(id  integer primary key, col1 text,col2 text); 
 insert into test1(id, col1, col2)
    values (1, 'John Doe', 'USA')
         , (2, 'Jane Doe', 'UK');
 select * from test1; 

 -- test on conflict
 insert into test1 as t(id, col1, col2)     
      values (3, 'Kate Bill', 'Canada')
           , (2, null, 'USA')
    on conflict(id) do update   
       set col1 = coalesce(excluded.col1,  t.col1)
         , col2 = coalesce(excluded.col2,  t.col2);

-- validate
 select * from test1;     
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Postgres ON CONFLICT DO 仅更新 python 中的非空值 的相关文章