令人费解的“重复密钥”错误(PostgreSQL)
问题描述:
首先,让我说我理解关系理论,我和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)
一样的东西!那么它可能是什么?
答
您可能已载入表格中的数据,但忽略将service_id_seq
的当前值设置为必要值。您可以只需SELECT * FROM service_id_seq
来检查当前值,并使用setval
函数重置它。例如,SELECT setval('service_id_seq'::regclass, MAX(id)) FROM service;
应该将该序列重置为表中的当前最大值。
我有同样的问题,我正在使用OpenJPA,我该如何解决它? – 2013-07-02 09:57:40