我需要重新编号数据库的行。删除一些行后,我必须重新编号某列。如何使用postgresql
?
更新: 例如: 我有一张这样的桌子:
ac_n_circ name
1 x
2 y
8 c
15 b
我想像这样重新编号这个表:
ac_n_circ name
1 x
2 y
3 c
4 b
在posgresql中是否有任何算法或类似的东西?
谢谢!
答案 0 :(得分:2)
ac_n_circ
NOT 主键列时才有意义。如果你确定你需要这个(你真的吗?),那么下面的内容应该有效:
with new_numbers as (
select row_number() over (order by ac_n_circ) as new_nr,
ac_n_circ,
id
from foo
)
update foo
set ac_n_circ = nn.new_nr
from new_numbers nn
where nn.id = foo.id;
或者:
update foo
set ac_n_circ = nn.new_number
from (
select id,
ac_n_circ,
row_number() over (order by ac_n_circ) as new_number
from foo
) nn
where nn.id = foo.id;
两个语句都假定有一个名为id
的主键列。