在几行中增加唯一值

Increase unique value in few row

我将 table 创建为

create table public.test
(
    val int unique not null
)

这 table 包含一些行

|   Val  |
|--------|
|1       |
|2       |
|3       |
|4       |
|5       |
|6       |
|7       |
|8       |
|9       |

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

ERROR: duplicate key value violates unique constraint "test_val_key" DETAIL: Key (val)=(7) already exists.

我该怎么做?

一种选择是删除唯一约束,然后再将其添加回来。

另一种选择是破解:

update public.test
    set val = - val
    where val > 5;

update public.test
    set val = (- val) + 1
    where val < 0;

如果您需要定期执行此操作,则应将约束创建为可延迟的:

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

要使预期的更新生效,没有必要将约束标记为 initially deferredchange the constraints 以在会话中延迟。

在上述约束条件下,以下更新工作正常:

update test set val=val+1 where val > 5;

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

选项没有 deferrable initially immediate

update test t1
set val=t2.val+1
from (select val from test order by val desc) t2
where t2.val > 5 and t1.val=t2.val

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

检查排序是否保存的在线示例:http://rextester.com/FAU54991