在 postgresql 9.5 中是否可以从 WITH 查询中插入冲突更新?
is INSERT ON CONFLICT UPDATE from WITH query possible in postgresql 9.5?
我正在尝试从 CTE 插入(或更新冲突)行,但很难找到正确的语法。我要插入的 table 看起来像这样(为清楚起见进行了简化)
Column | Type | Modifiers
----------------------+--------------------------+------------------------------------------------------------------
id | integer | not null default nextval('"QuestionStatistic_id_seq"'::regclass)
questionId | integer |
count | integer | not null default 0
Indexes:
"QuestionStatistic_pkey" PRIMARY KEY, btree (id)
"QuestionStatistic_questionId_key" UNIQUE CONSTRAINT, btree ("questionId")
这是我的查询:
with "Statistic" as (
select "questionId", "count" from "SomeTable"
)
INSERT INTO "QuestionStatistic" ("questionId", "count") SELECT "questionId", "count" FROM "Statistics"
ON CONFLICT ("questionId") DO UPDATE SET "count" = "Statistics"."count"
这在 SET "count" = "Statistics"."count"
部分给了我 ERROR: missing FROM-clause entry for table "Statistics"
。
我还尝试将 FROM 添加到更新子句但得到 ERROR: syntax error at or near "FROM"
。有没有办法让 INSERT ON CONFLICT UPDATE 与 CTE 一起工作?
https://www.postgresql.org/docs/9.5/static/sql-insert.html
The SET
and WHERE
clauses in ON CONFLICT DO UPDATE
have access to the existing row using the table's name (or an alias), and to rows proposed for insertion using the special excluded
table.
因此尝试:
with "Statistic" as (
select "questionId", "count" from "SomeTable"
)
INSERT INTO "QuestionStatistic" ("questionId", "count")
SELECT "questionId", "count" FROM "Statistics"
ON CONFLICT ("questionId") DO UPDATE
SET "count" = excluded."count"
我正在尝试从 CTE 插入(或更新冲突)行,但很难找到正确的语法。我要插入的 table 看起来像这样(为清楚起见进行了简化)
Column | Type | Modifiers
----------------------+--------------------------+------------------------------------------------------------------
id | integer | not null default nextval('"QuestionStatistic_id_seq"'::regclass)
questionId | integer |
count | integer | not null default 0
Indexes:
"QuestionStatistic_pkey" PRIMARY KEY, btree (id)
"QuestionStatistic_questionId_key" UNIQUE CONSTRAINT, btree ("questionId")
这是我的查询:
with "Statistic" as (
select "questionId", "count" from "SomeTable"
)
INSERT INTO "QuestionStatistic" ("questionId", "count") SELECT "questionId", "count" FROM "Statistics"
ON CONFLICT ("questionId") DO UPDATE SET "count" = "Statistics"."count"
这在 SET "count" = "Statistics"."count"
部分给了我 ERROR: missing FROM-clause entry for table "Statistics"
。
我还尝试将 FROM 添加到更新子句但得到 ERROR: syntax error at or near "FROM"
。有没有办法让 INSERT ON CONFLICT UPDATE 与 CTE 一起工作?
https://www.postgresql.org/docs/9.5/static/sql-insert.html
The
SET
andWHERE
clauses inON CONFLICT DO UPDATE
have access to the existing row using the table's name (or an alias), and to rows proposed for insertion using the specialexcluded
table.
因此尝试:
with "Statistic" as (
select "questionId", "count" from "SomeTable"
)
INSERT INTO "QuestionStatistic" ("questionId", "count")
SELECT "questionId", "count" FROM "Statistics"
ON CONFLICT ("questionId") DO UPDATE
SET "count" = excluded."count"