2011-02-28 36 views
4

首先,讓我說我理解關係理論,我和MySQL中的任何人一樣勝任,但我是一個完全PostgreSQL noob。令人費解的「重複密鑰」錯誤(PostgreSQL)

當我嘗試插入新記錄到我service表 - 只有在生產 - 我得到這樣的:

ActiveRecord::RecordNotUnique (PGError: ERROR: duplicate key value violates unique constraint "service_pkey" 
: INSERT INTO "service" ("created_at", "name", "salon_id", "updated_at") VALUES ('2011-02-28 02:34:20.054269', 'Manicure', 1, '2011-02-28 02:34:20.054269') RETURNING "id"): 
    app/controllers/services_controller.rb:46 
    app/controllers/services_controller.rb:45:in `create' 

我不明白爲什麼。它不應該爲我自動增加PK嗎?

這裏的表定義:

snip=> \d service 
            Table "public.service" 
    Column |   Type    |      Modifiers      
------------+-----------------------------+------------------------------------------------------ 
id   | integer      | not null default nextval('service_id_seq'::regclass) 
name  | character varying(255)  | 
salon_id | integer      | 
created_at | timestamp without time zone | 
updated_at | timestamp without time zone | 
Indexes: 
    "service_pkey" PRIMARY KEY, btree (id) 

而這裏的定義是相同的表中發展,在那裏工作得很好:

snip_development=> \d service 
            Table "public.service" 
    Column |   Type    |      Modifiers      
------------+-----------------------------+------------------------------------------------------ 
id   | integer      | not null default nextval('service_id_seq'::regclass) 
name  | character varying(255)  | 
salon_id | integer      | 
created_at | timestamp without time zone | 
updated_at | timestamp without time zone | 
Indexes: 
    "service_pkey" PRIMARY KEY, btree (id) 

一樣的東西!那麼它可能是什麼?

回答

15

您可能已載入表格中的數據,但忽略將service_id_seq的當前值設置爲必要值。您可以只需SELECT * FROM service_id_seq來檢查當前值,並使用setval函數重置它。例如,SELECT setval('service_id_seq'::regclass, MAX(id)) FROM service;應該將該序列重置爲表中的當前最大值。

+0

我有同樣的問題,我正在使用OpenJPA,我該如何解決它? – 2013-07-02 09:57:40