This question already has answers here:
Shift (update) unique column values in PostgreSQL

(2 个回答)


2年前关闭。




我有表创建为
create table public.test
(
    val int unique not null
)

此表包含一些行
|   Val  |
|--------|
|1       |
|2       |
|3       |
|4       |
|5       |
|6       |
|7       |
|8       |
|9       |

我想增加大于 5 的所有值(使用 PostgreSQL)。但是如果尝试 update public.test set val=val+1 where val > 5 我会得到异常:



我怎么能做到这一点?

最佳答案

如果您需要定期这样做,您应该将约束创建为可延迟:

create table test
(
    val int not null
);
alter table test
   add constraint unique_value unique(val)
   deferrable initially immediate;

为了使预期的更新工作,没有必要在 session 中将约束标记为 initially deferred 或将 change the constraints 标记为可延迟。

有了上述约束,以下更新工作得很好:
update test set val=val+1 where val > 5;

在线示例:http://rextester.com/KXI21597

关于sql - 在几行中增加唯一值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52386450/

10-11 02:44
查看更多