2015-10-13 85 views
1

這個問題幾乎就像How to reset postgres' primary key sequence when it falls out of sync?,除了我不使用序列,所以解決方案不適用。如何重置postgres的主鍵索引,如果它不同步

我有這樣創建的表:

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 | [email protected] |  2 
(2 rows) 

但是現在我得到關於第三個錯誤(這可能是在第Ë截斷):

> insert into contact(name, email, phone_number, unit_id) 
    select 'S S','[email protected]', '+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上運行。

+0

'truncate'成功了嗎? 'select count(*)from contact' –

+0

it did。 '計數(1行)' – eis

+0

那裏以前有100多行,但正如你可以從select語句看到的那樣,現在只有兩行。 – eis

回答

0

這是通過@a_horse_with_no_name在註釋中解決的。我在單元表中有一些重複的條目,導致多個相同的條目被同時插入,導致錯誤。主鍵索引在這裏並不完全是錯誤的,而是暗示我的另一個問題。

添加它作爲答案,所以我可以將其標記爲已回答。如果@a_horse_with_no_name會提供他自己的答案,我會將其標記爲已接受的並將其刪除。

相關問題