gpt4 book ai didi

sql - 如何在 postgres 9.5 中正确执行 upsert

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

upsert 与 postgresql 9.5 的正确语法,下面的查询显示 column reference "gallery_id"is ambiguous 错误,为什么?

var dbQuery = `INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id)
DO UPDATE SET
category_id = $1,
last_modified_date = $3,
last_modified_by_user_id = $4
WHERE gallery_id = $2`;

我尝试将 WHERE gallery_id = $2; 更改为 WHERE category_gallery.gallery_id = $2; 然后显示错误 没有与 ON CONFLICT 匹配的唯一或排除约束specification,但我不想将 gallery_id 或 category_id 设置为唯一,因为我想确保两列相同,然后进行更新....

如何在 postgres 9.5 中正确执行 upsert?

如果 ON CONFLICT 需要唯一列,我应该使用其他方法吗?如何?



我想确定多个列都冲突然后做更新,什么是正确的用法

var dbQuery = `INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id, gallery_id)
DO UPDATE SET
category_id = $1,
last_modified_date = $3,
last_modified_by_user_id = $4
WHERE gallery_id = $2`;


var dbQuery = `INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id AND gallery_id)
DO UPDATE SET
category_id = $1,
last_modified_date = $3,
last_modified_by_user_id = $4
WHERE gallery_id = $2`;

表(category_id,gallery_id 不是唯一的列)

category_id | gallery_id | create_date | create_by_user_id | last_modified_date | last_modified_by_user_id
1 | 1 | ...
1 | 2 | ...
2 | 2 | ...
1 | 3 | ...

最佳答案

ON CONFLICT 结构需要一个UNIQUE 约束才能工作。来自 INSERT .. ON CONFLICT clause 上的文档:

The optional ON CONFLICT clause specifies an alternative action to raising a unique violation or exclusion constraint violation error. For each individual row proposed for insertion, either the insertion proceeds, or, if an arbiter constraint or index specified by conflict_target is violated, the alternative conflict_action is taken. ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action. ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.

现在,问题不是很清楚,但您可能需要对 2 列组合的 UNIQUE 约束:(category_id, gallery_id)

ALTER TABLE category_gallery
ADD CONSTRAINT category_gallery_uq
UNIQUE (category_id, gallery_id) ;

如果要插入的行与表中已有行的两个值匹配,则执行UPDATE,而不是INSERT:

INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id, gallery_id)
DO UPDATE SET
last_modified_date = EXCLUDED.create_date,
last_modified_by_user_id = EXCLUDED.create_by_user_id ;

您可以使用 UNIQUE 约束的任一列:

  ON CONFLICT (category_id, gallery_id) 

或约束名称:

  ON CONFLICT ON CONSTRAINT category_gallery_uq  

关于sql - 如何在 postgres 9.5 中正确执行 upsert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799104/

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