将没有主键的 table 中的数据复制到带有 pk 的 table
Copying data from table without primary key to a table with a pk
我在 Postgres 中有两个 tables foo
和 bar
具有相同的结构,只是 bar
是空的并且有一个名为 [=16= 的主键],而 foo
已填充,并且有一个名为 id
的列具有唯一值(但它没有主键)。
当我尝试使用此命令将数据从 foo
复制到 bar
时:
INSERT INTO bar
SELECT id, timestamp, updated_at
FROM foo
我得到一个错误:
ERROR: duplicate key value violates unique constraint "bar_pkey"
DETAIL: Key (id)=(1) already exists.
当 table bar
完全为空时,为什么会出现此错误?在 postgres 中执行从没有主键的 table 到有主键的 table 的数据复制的正确过程是什么?
验证 bar
确实为空:
select count(*)
from bar;
如果这不是问题,那么 foo
有重复项:
select id
from foo
group by id
having count(*) > 1;
还有其他神秘的可能性,例如错误命名的约束(因此问题实际上不是 id
)或触发器。但是,我不考虑这些可能性。
如果你想要每个 foo 任意一行,你可以使用 distinct on
:
select distinct on (id) id, timestamp, updated_at
from foo
order by id;
我在 Postgres 中有两个 tables foo
和 bar
具有相同的结构,只是 bar
是空的并且有一个名为 [=16= 的主键],而 foo
已填充,并且有一个名为 id
的列具有唯一值(但它没有主键)。
当我尝试使用此命令将数据从 foo
复制到 bar
时:
INSERT INTO bar
SELECT id, timestamp, updated_at
FROM foo
我得到一个错误:
ERROR: duplicate key value violates unique constraint "bar_pkey"
DETAIL: Key (id)=(1) already exists.
当 table bar
完全为空时,为什么会出现此错误?在 postgres 中执行从没有主键的 table 到有主键的 table 的数据复制的正确过程是什么?
验证 bar
确实为空:
select count(*)
from bar;
如果这不是问题,那么 foo
有重复项:
select id
from foo
group by id
having count(*) > 1;
还有其他神秘的可能性,例如错误命名的约束(因此问题实际上不是 id
)或触发器。但是,我不考虑这些可能性。
如果你想要每个 foo 任意一行,你可以使用 distinct on
:
select distinct on (id) id, timestamp, updated_at
from foo
order by id;