微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – 指向重复约束值的Upsert错误(On Conflict Do Update)

当我尝试在FROM语句中使用多个源时,我在Postgres 9.5中遇到ON CONFLICT DO UPDATE的问题.

工作代码示例:

INSERT INTO new.bookmonographs  (citavi_id,abstract,createdon,edition,title,year)
SELECT "ID","Abstract","CreatedOn"::timestamp,"Edition","Title","Year"
FROM old."Reference"
WHERE old."Reference"."ReferenceType" = 'Book'
    AND old."Reference"."Year" IS NOT NULL
    AND old."Reference"."Title" IS NOT NULL
ON CONFLICT (citavi_id) DO UPDATE 
    SET (abstract,year) = (excluded.abstract,excluded.createdon,excluded.edition,excluded.title,excluded.year)
;

错误代码

INSERT INTO new.bookmonographs  (citavi_id,"Year"
FROM old."Reference",old."ReferenceAuthor"
WHERE old."Reference"."ReferenceType" = 'Book'
    AND old."Reference"."Year" IS NOT NULL
    AND old."Reference"."Title" IS NOT NULL
    AND old."ReferenceAuthor"."ReferenceID" = old."Reference"."ID"
    --Year,Title and Author must be present in the data,otherwise the entry is deemed useless,hence won't be included
ON CONFLICT (citavi_id) DO UPDATE 
    SET (abstract,excluded.year)
;

我在FROM语句中添加一个额外的源,还有一个WHERE语句,以确保只有具有title,year和author的条目插入到新数据库中. (如果旧的话.“引用”.“ID”存在于旧的中.“ReferenceAuthor”作为“ReferenceID”,然后作者存在.)即使没有附加的WHERE语句,查询也是错误的.我在SELECT中指定的列只出现在old.“Reference”中,而不是旧的.“ReferenceAuthor”.
目前陈旧.“ReferenceAuthor”和旧的.“参考”没有独特的约束,书籍专用的唯一约束是:

CONSTRAINT bookmonographs_pk PRIMARY KEY (bookmonographsid),CONSTRAINT bookmonographs_bookseries FOREIGN KEY (bookseriesid)
      REFERENCES new.bookseries (bookseriesid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT bookmonographs_citaviid_unique UNIQUE (citavi_id)

错误Psql抛出:

ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
HINT: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.
********** Error **********

ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
sql state: 21000
Hint: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.

我不知道什么是错的,或者为什么提示指向重复的约束值.

解决方法

问题是由于显然某些条目有多个作者.因此,您编写的select查询中的内部联接将为同一条目返回多行并且INSERT … ON CONFLICT不喜欢这样.由于您只使用ReferenceAuthor表进行过滤,因此您只需重写查询,以便它使用该表仅通过在相关子查询上执行存在来过滤没有任何作者的条目.这是如何做:

INSERT INTO new.bookmonographs  (citavi_id,"Year"
FROM old."Reference"
WHERE old."Reference"."ReferenceType" = 'Book'
    AND old."Reference"."Year" IS NOT NULL
    AND old."Reference"."Title" IS NOT NULL
    AND exists(SELECT FROM old."ReferenceAuthor" WHERE old."ReferenceAuthor"."ReferenceID" = old."Reference"."ID")
    --Year,excluded.year)
;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐