如何将现有数据的表主键从字符更改为序列

问题描述 投票:0回答:1

我正在和一位刚接触 Postgres 和数据库的同事一起工作。她创建了一个表,该表的列 ID 为字符变化类型,并将其作为主键。显然,当运行 python 脚本来填充表时,她自己增加了 ID 并将它们作为字符串插入。她在表中插入了相当大量的数据,所以我想修复它而不是让她重新开始。我需要将 ID 列更改为串行类型(她应该一开始就这样做),但我认为我不能只更改类型,因为它包含字符数据。谁能告诉我解决这个问题的最佳方法?

postgresql primary-key
1个回答
1
投票

serial
不是真实类型。它是一个具有关联序列的整数列。更改现有列时,您必须自己完成这项工作。

我假设这些值是整数,它们只是存储为文本。

-- Alter the ID column to integer, and cast the values to integers
alter table test alter id type integer using id::integer;

-- Make the ID a generated identity. This is similar to serial.
-- It also creates a sequence.
alter table test alter id add generated by default as identity;

-- Sequences start at 1. This would likely cause a duplicate the next time
-- you inserted a row.
-- Find the sequence attached to the ID column, and change it to start at
-- the next highest ID.
select setval(pg_get_serial_sequence('test', 'id'), coalesce(max(id), 0)+1 , false) from test;

有关最后一句话的更多信息,请参阅此答案。请参阅这个答案了解序列号与身份。

示范.


如果 ID 值不是整数,则最好丢弃 ID 列并创建一个新列。这假设没有外键引用该 ID,因为这会变得复杂。

-- Drop the old one
alter table test drop id;

-- Add a new primary key.
-- Alternatively, you can `alter table test add id serial primary key`
alter table test add id integer primary key generated by default as identity;

新的 ID 列将按顺序填充:1, 2, 3, ...

示范.

© www.soinside.com 2019 - 2024. All rights reserved.