如果您添加这样的序列列,现有行将自动以“任意”顺序更新。
要控制生成 ID 的顺序,您需要分多个步骤执行此操作:
首先添加没有默认值的列(serial
意味着默认值)
ALTER TABLE tickets ADD COLUMN ticket_id integer;
然后创建一个序列来生成值:
create sequence tickets_ticket_id_seq;
然后更新现有行
update tickets
set ticket_id = t.new_id
from (
select id, nextval('tickets_ticket_id_seq') as new_id
from tickets
order by "date"
) t
where t.id = tickets.id;
然后将序列设为新列的默认值
alter table tickets alter column ticket_id set default nextval('tickets_ticket_id_seq');
最后,将序列与列相关联(这也是 aserial
在后台所做的):
alter sequence tickets_ticket_id_seq owned by tickets.ticket_id;
如果表真的很大(“数十”或“数亿”),那么创建一个新表可能会更快:
create sequence tickets_ticket_id_seq;
create table tickets_new
as
select id, nextval('activities_ticket_id_seq') ticket_id, "date", status
from tickets
order by "date";
drop table tickets cascade;
alter table tickets_new rename to tickets;
alter table tickets add primary key (id);
alter sequence tickets_ticket_id_seq owned by tickets.ticket_id;
然后为该表重新创建所有外键和索引。