如果唯一的列组合不存在,则插入 PostgreSQL table,如果存在,则更新现有记录
Insert into PostgreSQL table if a unique column combination doesn't exist, and if it does, update the existing record
我有一个 table 结构,包含列 user_id、item_id、测试
我想进行一个 INSERT/UPDATE 查询,这样如果传入的 user_id 和 item_id 组合已经在 table 的一行中找到,它只是更新该行的测试。我尝试了以下查询,但它不起作用:
INSERT INTO tableName (user_id, item_id, test)
VALUES(, , )
ON CONFLICT ON CONSTRAINT UNIQUE(user_id, item_id)
DO UPDATE SET test = ()
这行不通。我也尝试过使用 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
我有一个 table 结构,包含列 user_id、item_id、测试
我想进行一个 INSERT/UPDATE 查询,这样如果传入的 user_id 和 item_id 组合已经在 table 的一行中找到,它只是更新该行的测试。我尝试了以下查询,但它不起作用:
INSERT INTO tableName (user_id, item_id, test)
VALUES(, , )
ON CONFLICT ON CONSTRAINT UNIQUE(user_id, item_id)
DO UPDATE SET test = ()
这行不通。我也尝试过使用 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