postgresql alter table在created_at上添加具有排序值的列序列

时间:2017-07-20 19:37:50

标签: sql postgresql

我有用户表,现在我想添加一个串行列cid

用户:

 id    | username | email           | createdAt
-------------------------------------------------
"uuid" | "abc"    | "abc@gmail.com" | '2017-01-01'
"uuid" | "abc"    | "abc@gmail.com" | '2017-02-01'
"uuid" | "abc"    | "abc@gmail.com" | '2017-03-01'

我想添加一个列cid,其值为serial但不包含主键

  id   |username|     email       | createdAt    | cid
-------------------------------------------------------
"uuid" | "abc"  | "abc@gmail.com" | '2017-01-01' |  1
"uuid" | "abc"  | "abc@gmail.com" | '2017-02-01' |  2
"uuid" | "abc"  | "abc@gmail.com" | '2017-03-01' |  3
...

我尝试了什么:

alter table user add column cid serial not null;

但它会产生:

  id   |username|     email       | createdAt    | cid
-------------------------------------------------------
"uuid" | "abc"  | "abc@gmail.com" | '2017-01-01' | 4
"uuid" | "abc"  | "abc@gmail.com" | '2017-02-01' | 7
"uuid" | "abc"  | "abc@gmail.com" | '2017-03-01' | 3
....

我可以这样做:

alter table user add column cid serial not null order by createdAt

这样它可以生成预期结果,cid顺序值,按createdAt排序?

1 个答案:

答案 0 :(得分:1)

为什么要将它添加到表格中?你可以这样做:

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的顺序)作为seqnum           来自用户u          )uu          在u.uuid = uu.uuid