【问题标题】:Updating the values of Primary key columns in Postgresql在 Postgresql 中更新主键列的值
【发布时间】:2019-08-16 08:50:45
【问题描述】:
我有下表
| ID | Seq No|
+++++++++++++++
| 1 | 12345 |
| 2 | 12345 |
| 3 | 12345 |
| 4 | 12345 |
| 5 | 12345 |
这两列都是主键值。
对于大于 2 的 ID 值,我需要将值加 1。
以下是我尝试执行的查询
Update tblname
set id = id + 1
where id > 2 and seq_no = 12345
执行命令时出现如下错误
错误:重复的键值违反了唯一约束“tblname”
DETAIL: Key (id, seq_no)=(3, 12345) 已经存在。
我该如何解决这个问题。
PS:作为一种解决方法,我尝试将 ID 值加 10,然后再次从 ID 值中减去 9。
【问题讨论】:
标签:
database
postgresql
sql-update
【解决方案1】:
此解决方法涉及 2 个更新语句。
第一个将 ids 更新为负值,第二个将它们再次变为正值:
Update tblname
set id = -(id + 1)
where id > 2 and seq_no = 12345;
Update tblname
set id = -id
where id < -2 and seq_no = 12345;
请参阅demo。
结果:
| id | seq_no |
| --- | ------ |
| 1 | 12345 |
| 2 | 12345 |
| 4 | 12345 |
| 5 | 12345 |
| 6 | 12345 |
【解决方案2】:
我使用 WITH 子句找到了查询,但没有使用任何解决方法。
with target_records as (
select id, seq_no from tblname
where seq_no = 12345 and id > 2
order by id desc
)
--select * from target_records;
Update tblname
Set id = target_records.id + 1
from target_records
where tblname.id = target_records.id and tblname.seq_no = 12345;