【问题标题】:postgresql: copy missing records from one table to anotherpostgresql:将丢失的记录从一个表复制到另一个
【发布时间】:2016-05-27 14:38:56
【问题描述】:

我有两个表 public_a.budget_itemspublic_b.budget_items 具有相同的方案,我正在尝试使用此查询将丢失的记录从其中一个复制到另一个:

INSERT INTO public_b.budget_items
SELECT a.*
FROM   public_a.budget_items a
WHERE  a.id NOT IN (SELECT b.id
                    FROM   public_b.budget_items b
                    WHERE  b.id = a.id
                            OR ( b.budget_id = a.budget_id
                                 AND b.NAME = a.NAME
                                 AND b.type = a.type
                                 AND b.asset = a.asset ))

但我收到此错误:

错误:重复键值违反唯一约束“uc_budget_items_parent_null” SQL 状态:23505 详情:Key (budget_id, name, type, asset)=(3486, Octopus, 6, T) 已经存在

约束uc_budget_items_parent_null定义如下:

  CREATE UNIQUE INDEX uc_budget_items_parent_null ON budget_items USING btree (
budget_id, name, type, asset);  

我认为条件(b.budget_id=a.budget_id and b.name=a.name and b.type = a.type and b.asset = a.asset) 应该可以帮助我避免这个问题,但它似乎不起作用。

显然我在这里遗漏了一些东西。有什么想法吗?

【问题讨论】:

  • where a.id not in (select id from public_b.budget_items) 会工作吗?
  • @Bill No. 除了uc_budget_items_parent_null 这样的主键(id)之外,表中还有其他约束。我必须在查询中考虑这些约束。

标签: sql postgresql


【解决方案1】:

我认为你这里的递归太深了。试试这个:

INSERT INTO public_b.budget_items
SELECT    a.*
FROM      public_a.budget_items a
LEFT JOIN public_b.budget_items b
       ON b.id = a.id
       OR ( b.budget_id = a.budget_id
            AND b.NAME  = a.NAME
            AND b.type  = a.type
            AND b.asset = a.asset )
WHERE b.id Is NULL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多