1

我需要重新编号我的数据库的行。删除一些行后,我必须重新编号某些列。我怎样才能做到这一点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 中是否有任何算法或类似的东西可以做到这一点?

谢谢!

4

1 回答 1

3

警告:

ac_n_circ这仅在不是主键列时才有意义。

如果你确定你需要这个(你真的需要这个吗?),那么类似下面的东西应该可以工作:

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

于 2013-04-23T18:52:08.943 回答