我有用户表,现在我想添加一个串行列:
用户:
id | username | email | createdAt
-------------------------------------------------
"uuid" | "abc" | "[email protected]" | '2017-01-01'
"uuid" | "abc" | "[email protected]" | '2017-02-01'
"uuid" | "abc" | "[email protected]" | '2017-03-01'
我想添加一列cid,其值类似于
cid
但不是主键 id |username| email | createdAt | cid
-------------------------------------------------------
"uuid" | "abc" | "[email protected]" | '2017-01-01' | 1
"uuid" | "abc" | "[email protected]" | '2017-02-01' | 2
"uuid" | "abc" | "[email protected]" | '2017-03-01' | 3
...
我试过的:
alter table user add column cid serial not null;
但它产生了:
id |username| email | createdAt | cid
-------------------------------------------------------
"uuid" | "abc" | "[email protected]" | '2017-01-01' | 4
"uuid" | "abc" | "[email protected]" | '2017-02-01' | 7
"uuid" | "abc" | "[email protected]" | '2017-03-01' | 3
....
我能做点什么吗
alter table user add column cid serial not null order by createdAt
这样它就可以产生预期的结果,即
serial
有序的序列值? 最佳答案
为什么把它加到桌子上?你可以这样做:
select u.*, row_number() over (order by u.createdAt) as seqnum
from user u;
如果您在
user(createdAt)
上有一个索引,那么应该利用该索引。如果表中有唯一的列,则可以执行更新:
更新用户u
设置cid=uu.seqnum
from(选择u*,row_number()over(按u.createdAt排序)as seqnum
来自用户u
)uu公司
在u.uuid=uu.uuid上
关于sql - postgresql alter table在created_at上添加具有排序值的列序列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45223823/