我想插入名为" foo"的标记,除非它已经存在。所以我构造了以下查询:
INSERT INTO "tag" ("name") VALUES ('foo')
WHERE NOT EXISTS (SELECT 1 FROM "tag" WHERE ("tag"."name" = 'foo'));
但是这会因以下错误而失败:
ERROR: syntax error at or near "WHERE"
LINE 1: INSERT INTO "tag" ("name") VALUES ('foo') WHERE NOT EXISTS (...
^
我不明白该查询的问题在哪里。特别是,因为我可以提供子查询而不是VALUES
,突然间查询完全正常:
INSERT INTO "tag" ("name") SELECT 'foo' AS name
WHERE NOT EXISTS (SELECT 1 FROM "tag" WHERE ("tag"."name" = 'foo'));
这导致:
Query returned successfully: 0 rows affected, 11 ms execution time.
它是0行,因为标签已经存在。
答案 0 :(得分:3)
您可以,只需使用INSERT INTO "tag" ("name")
SELECT 'foo'
WHERE NOT EXISTS (SELECT 1 FROM "tag" WHERE ("tag"."name" = 'foo'));
表单。
{{1}}
然而,它并没有做你想要的。至少不在并发工作负载下。您仍然可以获得唯一的违规或重复插入。
请参阅: