小编典典

冲突后的Postgres确实会在复合主键上进行更新

sql

我有一个用户在其中回答问题的表。规则是用户可以回答许多问题,或者许多用户可以回答一个问题,但用户只能回答一次特定问题。如果用户再次回答该问题,则只需替换旧的问题即可。通常,当我们处理唯一列时,on冲突确实会更新。在这种情况下,列person_idquestion_id不能唯一。但是,两者的结合始终是唯一的。如何实现在冲突时会更新的插入语句?

CREATE TABLE "answer" (
  "person_id" integer NOT NULL REFERENCES person(id), 
  "question_id" integer NOT NULL REFERENCES question(id) ON DELETE CASCADE, /* INDEXED */
  "answer" character varying (1200) NULL,
  PRIMARY KEY (person_id, question_id) 
);

阅读 222

收藏
2021-03-23

共1个答案

小编典典

只需将两个键放在ON CONFLICT子句中:

INSERT INTO answer VALUES (1,1,'q1') 
ON CONFLICT (person_id,question_id) 
DO UPDATE SET answer = EXCLUDED.answer;

例子:

INSERT INTO answer VALUES (1,1,'q1') 
ON CONFLICT (person_id,question_id) 
DO UPDATE SET answer = EXCLUDED.answer;

SELECT * FROM answer;
 person_id | question_id | answer 
-----------+-------------+--------
         1 |           1 | q1
(1 Zeile)

INSERT INTO answer VALUES (1,1,'q1-UPDATED') 
ON CONFLICT (person_id,question_id) 
DO UPDATE SET answer = EXCLUDED.answer;

SELECT * FROM answer;
 person_id | question_id |   answer   
-----------+-------------+------------
         1 |           1 | q1-UPDATED
(1 Zeile)
2021-03-23