插入时在空 table 上持续 "unique constraint violation"

Persistent "unique constraint violation" on an empty table while inserting

假设我正在管理一个简单的 table。此外,每个用户都可以间接创建每一行的副本并自行修改。

这是我的设置:

-- 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 table 中的现有行。但是,以下本应完成这项工作的声明失败了:

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 table 完全是空的。前一个语句是唯一一个向 table 提供任何行的 INSERT 语句,但它以某种方式违反了唯一约束。在没有 SELECT 子查询的情况下手动插入值已成功执行。经过几个小时的研究,我 运行 不知道错误的原因是什么,我觉得这个问题的解决方案一定非常简单。我正在使用 PostgreSQL 9.4。

您需要为每条记录创建一个新的 ID。

而不是

INSERT INTO test_copy(copy_position, id, a, b, c)
    (SELECT 666, 3, t.a, t.b, t.c
        FROM test AS t);

测试中出现的每条记录始终使用 ID 3。

如果 id 是自动增量类型,请尝试以下代码。

INSERT INTO test_copy(copy_position, a, b, c)
    (SELECT 666, t.a, t.b, t.c
        FROM test AS t);

在这种情况下,您丢失了原始 ID。如果您需要保留原始 ID,则需要使用以下内容更改 table 结构:

CREATE TABLE test_copy
(
    copy_position integer NOT NULL, -- some additional data attached to the copy
    id integer PRIMARY KEY autoincrement,
    original_id FOREIGN KEY REFERENCES test(id), -- the id of the copied row
    a integer,
    b integer NOT NULL,
    c integer
);

插入内容变为:

INSERT INTO test_copy(copy_position, original_id, a, b, c)
        (SELECT 666, t.id, t.a, t.b, t.c
            FROM test AS t);

好吧,这个问题是一个完全无关紧要的问题。它在发布后的前两分钟内由 部分回答(谢谢),问题本身几乎是一个菜鸟错误。

我完全忘记了 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);

这就是这个问题。