Postgresql:如何在现有序列 ID 之后为空值设置 ID?

Postgresql: How can I set the id for null values following existed sequence id?

我有一个 table 有 1000 万条记录,大约有 100 万条记录的 ID 从 1-1 百万,大约有 900 万条记录有空值。如何使用现有 id 之后的 id 序列为空值设置 id。

在测试区试试这个,看看填充您的 table 需要多长时间。我们将在这里使用一个简短的例子。

create table test (id int, fullname text);
insert into test values (1, 'john');
insert into test values (2, 'john');
insert into test values (NULL, 'john');
insert into test values (NULL, 'john');

此模拟显示记录 1 和 2 有 ID,而记录 3 和 4 还没有 ID。

创建一个序列,我们将使用该序列填充记录 3 和 4 中的 ID。

create sequence populate_test start 3;

现在,让我们填充:

update test set id = nextval('populate_test') where id is null;

结果:

select * from test;
 id | fullname 
----+----------
  1 | john
  2 | john
  3 | john
  4 | john

在您的情况下,您可以尝试创建序列的 cache 选项,如下所示:create sequence populate_test start 3 cache 1000000; 一次缓存 1MM 数字。