簡體   English   中英

向 postgresql 中的列添加增量值

[英]Add incrementing value to the column in postgresql

我有一個包含69000 records的表。 現在,如何添加一個新列(比如索引),它應該包含第一行的value 1 for 1st row, 2 for 2nd row....etc

我想要以下結果

   id      name      index
 --------------------------
 9796896   sandy       1
 796869    raj         2

添加該列並使用類似以下內容進行更新:

with cte as
(
   select *
       , rank() over (order by id desc) as ranker
   from test
)
update test
   set index = ranker
from cte
where cte.id = test.id;

嘗試這個:

ALTER TABLE Tablename
    ADD COLUMN index int               
        GENERATED BY DEFAULT AS IDENTITY;

您可以使用oracle的身份列:

alter table your_Table add index_ number GENERATED by default as IDENTITY;

另外,您可以添加該列,然后為其分配值:

alter table your_Table add index_ number;

update your_Table tt
set tt.index_  =  (select rn from (
select row_number() over (order by id desc) rn
from your_Table t
) t where t.id = tt.id)

干杯!!

這對運行 postgres 9.6 的我來說效果很好:

ALTER TABLE test ADD COLUMN index BIGSERIAL ;

短一個襯里,它會在未來的插入中保持自動遞增。

盡管我認為計數是從零開始的。 檢查后我會更新答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM