postgresql - postgres:临时列默认值是唯一的且不可为空,不依赖于序列?
问题描述
- 嗨,我想向表中添加一个唯一的、不可为空的列。
- 它 已经有数据了。因此,我想立即用唯一值填充新列,例如“ABC123”、“ABC124”、“ABC125”等。
- 数据最终将被擦除并替换为适当的数据,所以我不想引入一个序列 来填充默认值。
是否可以基于类似的内容为现有行生成默认值rownumber()
?我意识到用例是荒谬的,但有可能实现......如果是这样怎么办?
...
foo text not null unique default 'ABC'||rownumber()' -- or something similar?
...
解决方案
可以应用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
推荐阅读
- c++ - 为什么我不能将左值引用绑定到右值,而概念可以?
- java - 将 springboot java RestHighLevelClient 连接到 aws elasticsearch
- flutter - 更改颜色 ListView.Builder onPressed Flutter
- c++ - 为什么我不能得到初始化列表提供的自定义概念的编译错误?
- x86-64 - 无法在真实硬件上设置视频模式,OSDEV
- mysql - 如何更新 3 个表 1 个查询
- git - 将 reflog 重置为当前 HEAD 位置的最快方法?
- gridsearchcv - GridSearchCV 找到最佳正则化参数:如何访问验证分数和训练分数
- flutter - Streambuilder 中的 Listviewer 无法正确更新已删除的对象
- django - 如何使用 Django 列表视图遍历 Chart.js