首页 > 解决方案 > postgres:临时列默认值是唯一的且不可为空,不依赖于序列?

问题描述

  1. 嗨,我想向表中添加一个唯一的、不可为空的列。
  2. 已经有数据了。因此,我想立即用唯一值填充新列,例如“ABC123”、“ABC124”、“ABC125”等。
  3. 数据最终将被擦除并替换为适当的数据,所以我不想引入一个序列 来填充默认值。

是否可以基于类似的内容为现有行生成默认值rownumber()?我意识到用例是荒谬的,但有可能实现......如果是这样怎么办?

...
foo text not null unique default 'ABC'||rownumber()' -- or something similar?
...

标签: postgresql

解决方案


可以应用generate_series吗?

select 'ABC' || generate_series(123,130)::text;

 ABC123
 ABC124
 ABC125
 ABC126
 ABC127
 ABC128
 ABC129
 ABC130

变体 2添加列UNIQUE且不为空

begin;
alter table test_table add column foo text not null default 'ABC';

with s as (select id,(row_number() over(order by id))::text t from test_table) update test_table set foo=foo || s.t from s where test_table.id=s.id;

alter table test_table add CONSTRAINT unique_foo1 UNIQUE(foo);

commit;

结果

select * from test_table;
id | foo
----+------
  1 | ABC1
  2 | ABC2
  3 | ABC3
  4 | ABC4
  5 | ABC5
  6 | ABC6

推荐阅读