gpt4 book ai didi

postgresql on conflict-cannot affect row 第二次

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

我有一张表,我在 data_id 上有自动编号/序列

tabledata
---------
data_id [PK]
data_code [Unique]
data_desc

示例代码:

insert into tabledata(data_code,data_desc) values(Z01,'red')
on conflict (data_code) do update set data_desc=excluded.data_desc

工作正常,然后我再次插入

insert into tabledata(data_code,data_desc) values(Z01,'blue')
on conflict (data_code) do update set data_desc=excluded.data_desc

我遇到了这个错误

[Err] ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time HINT: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.

这是我的真实代码

insert into psa_aso_branch(branch_code,branch_desc,regional_code,status,created_date,lastmodified_date) 
(select branch_code, branch, kode_regional,
case when status_data='Y' then true
else false end, current_date, current_date
from branch_history) on conflict (branch_code) do
update set branch_desc = excluded.branch_desc, regional_code = excluded.regional_code,status = (case when excluded.status='Y' then true else false end), created_date=current_date, lastmodified_date=current_date;

第一个工作正常,但下一个就不行(就像我之前给你的例子)

最佳答案

您可以在现有记录/行上使用更新,而不是在您要插入的行上。

此处 on conflict 子句中的 update 应用于排除表中的行,该表临时保留行。

在第一种情况下,插入记录是因为 data_code 上没有冲突,根本不执行更新。

在第二个插入中,您将插入 Z01,它已作为 data_code 插入,并且 data_code 是唯一的。

excluded表更新后仍然持有data_code的重复值,所以没有插入记录。在 更新集 中,必须更改 data_code 才能正确插入记录。

关于postgresql on conflict-cannot affect row 第二次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42994373/

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