PostgreSQL/Psycopg2 upsert 语法更新列

Dob*_*bob 6 postgresql insert python upsert

当出现 id 冲突时,我想让 Psycopg2 更新col1col2col3

在我的 Python 代码中,我目前的插入 SQL 为:

insert_sql = '''INSERT INTO {t} (id,col1,col2,col3)
        VALUES (%s,%s,NULLIF(%s, 'nan'), NULLIF(%s, 'nan'))
        ON CONFLICT (id)
        DO NOTHING;'''
Run Code Online (Sandbox Code Playgroud)

基本上我想设置而不是什么都不做:

(col1,col2,col3) = (%s,NULLIF(%s, 'nan'), NULLIF(%s, 'nan'))

忽略插入 ID 并更新 col1、col2 和 col3。问题是%s使用 Psycopg2 在 Python 中传递元组变量:

cur.execute(insert_sql.format(t='my_table'),(int(id),new_col1,new_col2,new_col3))
Run Code Online (Sandbox Code Playgroud)

用于引用%s对应于 col1、col2 和 col3 以更新 ON CONFLICT的语法是什么?

ype*_*eᵀᴹ 15

您可以使用EXCLUDED关键字来访问传递给 的值INSERT。无需通过它们两次:

insert_sql = '''
   INSERT INTO {t} (id,col1, col2, col3)
        VALUES (%s, %s, NULLIF(%s, 'nan'), NULLIF(%s, 'nan'))
        ON CONFLICT (id)
        DO UPDATE SET
            (col1, col2, col3)
            = (EXCLUDED.col1, EXCLUDED.col2, EXCLUDED.col3) ;
'''
Run Code Online (Sandbox Code Playgroud)

请参阅 Postgres 文档中关于ON CONFLICT.