简体   繁体   English

如何填充可为空的整数列并将其转换为Postgresql中的串行主键?

[英]How to fill a nullable integer column and convert it into a serial primary key in Postgresql?

My table contains an integer column ( gid ) which is nullable: 我的表包含一个可为空的整数列( gid ):

 gid | value
-------------
  0  |   a
     |   b
  1  |   c
  2  |   d
     |   e

Now I would like to change the gid column into a SERIAL primary key column. 现在,我想将gid列更改为SERIAL主键列。 That means filling up the empty slots with new integers. 这意味着用新的整数填充空插槽。 The existing integers must remain in place. 现有整数必须保留在原位。 So the result should look like: 因此结果应如下所示:

 gid | value
-------------
  0  |   a
  3  |   b
  1  |   c
  2  |   d
  4  |   e

I just can't figure out the right SQL command for doing the transformation. 我只是想不出正确的SQL命令来进行转换。 Code sample would be appreciated... 代码示例将不胜感激...

A serial is "just" a column that takes it default value from a sequence. serial是“只是”从序列中获取其默认值的列。 Assuming your table is named n1000 then the following will do what you want. 假设您的表名为n1000则以下操作将满足您的要求。

The first thing you need to do is to create that sequence: 您需要做的第一件事是创建该序列:

create sequence n1000_gid_seq;

Then you need to make that the "default" for the column: 然后,您需要将该列设置为“默认”:

alter table n1000 alter column gid set default nextval('n1000_gid_seq');

To truly create a "serial" you also need to tell the sequence that it is associated with the column: 要真正创建“序列”,还需要告诉序列它与列相关联:

alter sequence n1000_gid_seq owned by n1000.gid;

Then you need to advance the sequence so that the next value doesn't collide with the existing values: 然后,您需要推进序列,以使下一个值不与现有值冲突:

select setval('n1000_gid_seq', (select max(gid) from n1000), true);

And finally you need to update the missing values in the table: 最后,您需要更新表中的缺失值:

update n1000 
  set gid = nextval('n1000_gid_seq')
where gid is null;

Once this is done, you can define the column as the PK: 完成此操作后,您可以将列定义为PK:

alter table n1000 
   add constraint pk_n1000
   primary key (gid);

And of course if you have turned off autocommit you need to commit all this. 当然,如果您关闭了自动提交功能,则需要commit所有这些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM