- 嗨,我想向表中添加一個唯一的、不可為空的列。
- 它 已經有了資料。因此,我想立即用唯一值填充新列,例如“ABC123”、“ABC124”、“ABC125”等。
- 資料最終將被擦除并替換為正確的資料,所以我不想引入一個序列 來填充默認值。
是否可以基于類似的內容為現有行生成默認值rownumber()?我意識到用例很荒謬,但是否有可能實作……如果是這樣,如何實作?
...
foo text not null unique default 'ABC'||rownumber()' -- or something similar?
...
uj5u.com熱心網友回復:
可以應用generate_series嗎?
select 'ABC' || generate_series(123,130)::text;
ABC123
ABC124
ABC125
ABC126
ABC127
ABC128
ABC129
ABC130
變體 2添加列UNIQUE而不是 null
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/349166.html
標籤:PostgreSQL
上一篇:PostgresqlTIMESTAMP和TIMESTAMPTZ:存盤的資料有什么區別嗎?
下一篇:使用Doobie映射多對多關系
