簡體   English   中英

如果唯一列組合不存在,則插入 PostgreSQL 表,如果存在,則更新現有記錄

[英]Insert into PostgreSQL table if a unique column combination doesn't exist, and if it does, update the existing record

我有一個包含 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 關鍵字,但未能使其正常工作。 非常感謝任何幫助!

您需要在兩列上都有一個唯一索引。 它可以是復合主鍵或復合唯一約束,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM