这题跟How to reset postgres' primary key sequence when it falls out of sync?差不多,但我没有使用序列,所以那里的解决方案不适用。
我有一个这样创建的表:
create table contact (
name varchar(256) null,
phone_number varchar(256) constraint phone_number_id primary key,
email varchar(256) null,
unit_id int not null references unit(id)
);
以前有很多内容,我把它截断了
truncate contact cascade;
现在,尝试输入新数据,前两个很好:
> select * from contact;
name | phone_number | email | unit_id
------------------+---------------+-------------------------+---------
ETUNIMI SUKUNIMI | PUHELIN | SÄHKÖPOSTI | 1
J P | +3584053xx285 | j.p@xxxxxxxxxxxxxxxxxxx | 2
(2 rows)
但现在我收到关于第三个错误的错误(可能在截断之前就存在):
> insert into contact(name, email, phone_number, unit_id)
select 'S S','s.s@xxxxxxx', '+35840xxxx781', id from unit where name = 'Piiritoimisto';
ERROR: duplicate key value violates unique constraint "phone_number_id"
DETAIL: Key (phone_number)=(+35840xxxx781) already exists.
如何告诉 PostgreSQL 重置约束?以后我需要重复这个过程,并指导其他人这样做(使用可能有错误的数据),所以我不想只禁用约束。
我已经试过了
REINDEX index phone_number_id;
REINDEX table contact;
但他们没有帮助。还尝试了 COMMIT;
,它说没有事务正在进行。
PostgreSQL 版本 9.3.9,在 Ubuntu 上运行。
最佳答案
这由评论中的@a_horse_with_no_name 解决了。我在单元表中有一些重复的条目,导致同时插入多个相同的条目,从而导致错误。主键索引在这里完全没有错,而是暗示了我的其他问题。
将其添加为答案,以便我可以将其标记为已回答。如果@a_horse_with_no_name 将提供他自己的答案,我会将其标记为已接受并删除它。
关于postgresql - 如果不同步,如何重置 postgres 的主键索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33104970/