【问题标题】:Copying data from table without primary key to a table with a pk将没有主键的表中的数据复制到有 pk 的表中
【发布时间】:2021-07-07 16:44:07
【问题描述】:

我在 Postgres 中有两个表 foobar 具有相同的结构,除了 bar 是空的并且有一个名为 id 的主键,而 foo 已填充并有一个名为 @987654326 的列@ 具有唯一值(但它没有主键)。

当我尝试使用此命令将数据从 foo 复制到 bar 时:

INSERT INTO bar
SELECT id, timestamp, updated_at
FROM foo

我收到一个错误:

错误:重复键值违反唯一约束“bar_pkey”
详细信息:键 (id)=(1) 已存在。

当表 bar 完全为空时,如何可能出现此错误?在 postgres 中,将数据从没有主键的表复制到有主键的表的正确过程是什么?

【问题讨论】:

  • 大概foo 有重复。如果你 select idselect distinct id 有不同的行数吗
  • 不,foo 中没有重复项

标签: sql postgresql sql-insert primary-key


【解决方案1】:

验证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;

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2022-08-04
    • 1970-01-01
    • 2022-11-13
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多