我有两个表public_a.budget_items
和public_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 细节:密钥(budget_id,名称,类型,资产)=(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)
可以帮助我避免这个问题,但它似乎无法发挥作用。
显然,我在这里遗漏了一些东西。有什么想法吗?
答案 0 :(得分: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