【问题标题】:Insert into PostgreSQL table if a unique column combination doesn't exist, and if it does, update the existing record如果唯一的列组合不存在,则插入到 PostgreSQL 表中,如果存在,则更新现有记录
【发布时间】:2022-01-05 11:32:20
【问题描述】:

我有一个包含 user_id、item_id、test 列的表

我想做一个 INSERT/UPDATE 查询,这样如果传入的 user_id 和 item_id 组合已经在表的一行中找到,它只会更新该行的测试。我尝试了以下查询,但它不起作用:

INSERT INTO tableName (user_id, item_id, test) 
VALUES($1, $2, $3) 
ON CONFLICT ON CONSTRAINT UNIQUE(user_id, item_id) 
DO UPDATE SET test = ($3)

这不起作用。我也尝试过使用 DISTINCT 关键字,但未能使其正常工作。非常感谢任何帮助!

【问题讨论】:

    标签: sql postgresql upsert


    【解决方案1】:

    您需要在两列上都有一个唯一索引。可以是复合主键,也可以是复合唯一约束,例如:

    create table tablename(
        user_id int, 
        item_id int, 
        test text,
        primary key (user_id, item_id)
    );
    

    然后使用简单正确的语法:

    insert into tablename (user_id, item_id, test) 
    values(1, 1, '1') 
    on conflict (user_id, item_id) 
    do update set test = excluded.test
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-19
      • 2018-04-02
      • 2021-03-29
      • 2010-12-10
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多