假设我正在管理一个简单的表。此外,每个用户都可以间接创建每一行的副本并自行修改。
这是我的设置:
-- the original table
CREATE TABLE test
(
id integer PRIMARY KEY,
a integer,
b integer NOT NULL,
c integer
);
-- the table holding a modified copy of the former table
CREATE TABLE test_copy
(
copy_position integer NOT NULL, -- some additional data attached to the copy
id integer PRIMARY KEY REFERENCES test(id), -- the id of the copied row
a integer,
b integer NOT NULL,
c integer
);
-- some sample data
INSERT INTO test VALUES (1, 4, 4, 4), (2, 7, 3, 2), (3, 72, 23, 7), (4, 11, 22, 33);
我必须创建一个函数来复制 test
表中的现有行。但是,以下本应完成这项工作的声明失败了:
INSERT INTO test_copy(copy_position, id, a, b, c)
(SELECT 666, 3, t.a, t.b, t.c
FROM test AS t);
发出以下错误:
ERROR: duplicate key value violates unique constraint "test_copy_pkey"
DETAIL: Key (id)=(3) already exists.
test_copy
表完全是空的。前一个语句是唯一一个向表提供任何行的 INSERT
语句,但它以某种方式违反了唯一约束。在没有 SELECT
子查询的情况下手动插入值已成功执行。经过几个小时的研究,我想不出错误的原因是什么,我觉得这个问题的解决方案一定非常简单。我正在使用 PostgreSQL 9.4。
最佳答案
好吧,这个问题是一个完全无关紧要的问题。 @a_horse_with_no_name in the comments 在前两分钟内回答了这个问题发布后的部分(谢谢你),问题本身几乎是一个菜鸟错误。
我完全忘记了 SELECT
子查询中的 WHERE
子句。应该这样写:
INSERT INTO test_copy(copy_position, id, a, b, c)
(SELECT 666, t.id, t.a, t.b, t.c
FROM test AS t WHERE t.id = 3);
这就是这个问题。
关于sql - 插入时在空表上持续出现 "unique constraint violation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35312817/