【问题标题】:Duplicate key value violates unique constraint in postgres even though key does not exist?即使键不存在,重复的键值也会违反 postgres 中的唯一约束?
【发布时间】:2016-10-05 16:09:03
【问题描述】:

我正在使用的查询如下 -

INSERT into mytable(id, tp, booleanOne, classification, booleantwo, created_at) 
        SELECT distinct uttv.id, true, false, uttv.type, false, uttv.created_at 
             FROM userTable tt WHERE booleantwo = false 
                AND type is not null 
                AND tt.id in ( 
      SELECT id from userTable WHERE status=12 AND  booleantwo=false AND booleanThree=false UNION SELECT id FROM userTable WHERE status=19
                   ) 
             AND not exists (select 1 from mytable rre where rre.id = tt.id) 

该表的主键是 mytable.id 运行此查询时,我不断看到以下错误 -

Key (id)=(2556) already exists.; nested exception is org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "mytable_modified_pkey

当我检查 mytable 时,我没有看到任何匹配 2556 的 id。

此查询作为 Spring Boot 项目的一部分运行,我将隔离级别设置为 Seriablizable。

我认为在查询中使用 UNION 可以确保没有重复的 id,然后在外部 SELECT 查询中使用 distinct 将进一步确保我们只插入非重复的。我知道这个错误正在发生,因为选择查询可能会返回一些重复项,但即便如此,您也会看到我正在使用 - “AND NOT EXISTS”,并确保如果 id 已经存在,则不要插入。

任何关于我为什么会看到此错误的意见将不胜感激。这个查询也很慢。

我还尝试只执行查询的 SELECT 部分,方法是按 id 分组并检查是否有任何 id 出现多次,但我没有看到任何记录。现在我可以看到有重复。

SELECT tags.tag_id, count(1) from (SELECT distinct uttv.id, true, false, uttv.type, false, uttv.created_at 
                 FROM userTable tt WHERE booleantwo = false 
                    AND type is not null 
                    AND tt.id in ( 
          SELECT id from userTable WHERE status=12 AND  booleantwo=false AND booleanThree=false UNION SELECT id FROM userTable WHERE status=19
                       ) as tags group by tags.tag_id having count(1) > 1

【问题讨论】:

  • 我不认为这是重复的。 INSERTstatement 没有 WHERE 子句。

标签: postgresql spring-boot


【解决方案1】:

我想说SELECTemployee 上存在唯一约束的列返回不止一行具有相同值的列。

【讨论】:

  • 没错,但如果我尝试区分查询中所有提及的 id ,为什么不能解决问题?
  • 这取决于确切的 SQL 语句和您从中选择的表...尝试先调试 SELECT 语句。
猜你喜欢
  • 2020-05-28
  • 2022-11-04
  • 2012-06-20
  • 2012-03-03
  • 2020-04-08
  • 2019-03-20
  • 1970-01-01
  • 2018-05-20
相关资源
最近更新 更多