基于排序列添加序列列

Ben*_*Ben 2 postgresql

我有一张表,其中有一列具有无序值。我想按降序排列此列并添加一列来记录其顺序。我的SQL代码是:

select *
into newtable
from oldtable
order by column_name desc;

alter table newtable add column id serial;
Run Code Online (Sandbox Code Playgroud)

这能实现我的目标吗?我知道 PostgreSQL 中的行没有固定的顺序。所以我对此不太确定。

Cra*_*ger 5

不要(ab)使用SERIALvia ALTER TABLE,而是在插入时生成它。

CREATE TABLE newtable (id serial unique not null, LIKE oldtable INCLUDING ALL);

INSERT INTO newtable 
SELECT nextval('newtable_id_seq'), *
FROM oldtable
ORDER BY column_name desc;
Run Code Online (Sandbox Code Playgroud)

这避免了表重写,并且与之前的方法不同,可以保证产生正确的排序。

(如果您希望它成为 PK,并且先前的表没有 PK,请更改unique not nullprimary key。如果先前的表有 PK,您需要使用LIKE排除 的变体constraints)。