【发布时间】: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子句。