update-from语句中的唯一约束违例

时间:2014-09-20 12:50:36

标签: postgresql postgresql-9.3

我有以下查询:

UPDATE "PostsTags"
SET "TagId" = "PostsTags"."TagId" #tgs."mainId"
FROM (
  SELECT t1."TagId" AS "mainId", t1.text AS "mainText", t2."TagId" AS "malformedId", t2.text AS "malformedText"
  FROM "TagTranslations" t1 
  INNER JOIN "TagTranslations" t2 ON t1.text = regexp_replace(t2.text, '^\s+','') AND t2.id != t1.id
  WHERE regexp_replace(t1.text, '^\s+','') = t1.text AND t1."language" = 'en-us'
) tgs
WHERE "PostsTags"."TagId" = tgs."malformedId" AND "PostsTags"."language" = 'en-us' AND "PostsTags"."PostId" = 281
RETURNING *

如您所见,我正在更新TagId = TagId(我正在为TagId列设置相同的值)。我收到了以下错误:

ERROR:  duplicate key value violates unique constraint "PostsTags_pkey"
DETAIL:  Key (language, "PostId", "TagId")=(en-us, 281, 10157) already exists.

有人可以告诉我,在我实际上没有改变任何事情时,我是否有可能收到这些违规行为?

1 个答案:

答案 0 :(得分:1)

#没有引入评论。它是按位XOR运算符。 The manual

对于以行尾结尾的评论,请使用-- THIS Is a Comment

UPDATE "PostsTags"
SET "TagId" = "PostsTags"."TagId" -- COMMENTED OUT: tgs."mainId"
FROM (
  SELECT t1."TagId" AS "mainId", t1.text AS "mainText", t2."TagId" AS "malformedId", t2.text AS "malformedText"
  FROM "TagTranslations" t1 
  INNER JOIN "TagTranslations" t2 ON t1.text = regexp_replace(t2.text, '^\s+','') AND t2.id != t1.id
  WHERE regexp_replace(t1.text, '^\s+','') = t1.text AND t1."language" = 'en-us'
) tgs
WHERE "PostsTags"."TagId" = tgs."malformedId" AND "PostsTags"."language" = 'en-us' AND "PostsTags"."PostId" = 281
-- RETURNING *
  ;
BTW:仍无法保证更新是正确的;子查询可以导致为给定的t2.TagId返回多个匹配的元组 - > tgs."malformedId" - > "postTags"."TagId"