【问题标题】:postgresql alter table add column serial with sort values on created_atpostgresql 更改表在 created_at 上添加具有排序值的列序列
【发布时间】:2017-12-26 16:31:45
【问题描述】:

我有用户表,现在我想添加一个串行列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

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

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

    select u.*, row_number() over (order by u.createdAt) as seqnum
    from user u;
    

    如果您在user(createdAt) 上有索引,那么这应该利用索引。

    如果表中有唯一列,则可以进行更新:

    更新用户 u 设置 cid = uu.seqnum from (select u.*, row_number() over (order by u.createdAt) as seqnum 来自用户你 ) 你 关于 u.uuid = uu.uuid

    【讨论】:

    • 感谢您的快速回答.....是的,我必须添加该列,因为我的 id 列是一个 uuid,因此需要一个具有序列号的单独列
    • 我也试过update user set cid = row_number() over (order by user.createdAt)但抛出错误
    猜你喜欢
    • 1970-01-01
    • 2015-10-04
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多