gpt4 book ai didi

sql - 发生冲突的 Postgres 会更新复合主键

转载 作者:行者123 更新时间:2023-11-29 11:20:22 25 4
gpt4 key购买 nike

我有一张表格,用户可以在其中回答问题。规则是用户可以回答许多问题,或者许多用户可以回答一个问题,但一个用户只能回答一个特定问题一次。如果用户再次回答这个问题,它应该简单地替换旧的。通常,当我们处理唯一列时,on conflict do update 起作用。在这种情况下,列 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)
);

最佳答案

只需将两个键都放在 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')
ON CONFLICT (person_id,question_id)
DO UPDATE SET answer = EXCLUDED.answer || '-UPDATED';

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

演示: db<>fiddle

PostgreSQL 15 +

您也可以使用 MERGE 获得相同的结果:

MERGE INTO answer i
-- records to be inserted
USING (
VALUES (1,1,'q1'), -- already exists in table answers!
(2,2,'q2') -- new record
) AS j (person_id, question_id, answer)
-- checking if the PK of given records (j) already exists
-- in table "answer" (i).
ON j.question_id = i.question_id AND j.person_id = i.person_id
WHEN MATCHED THEN
-- in case of a match (conflict), I want to add the suffix '-UPDATED'
-- to the column "answer"
UPDATE SET answer = j.answer || '-UPDATED'
WHEN NOT MATCHED THEN
-- if there is no match (conflict) just INSERT the record.
INSERT (person_id, question_id, answer)
VALUES (j.person_id, j.question_id, j.answer);

演示: db<>fiddle

关于sql - 发生冲突的 Postgres 会更新复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51375439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com