是否可以在 postgresql 9.5 中从 WITH 查询插入冲突更新?

fou*_*shw 3 sql postgresql with-statement common-table-expression postgresql-9.5

我正在尝试从 CTE 插入(或更新冲突)行,但正在努力为其找到正确的语法。我插入的表格看起来像这样(为了清楚起见简化了)

        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")
Run Code Online (Sandbox Code Playgroud)

这是我的查询:

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"
Run Code Online (Sandbox Code Playgroud)

这使我ERROR: missing FROM-clause entry for table "Statistics"SET "count" = "Statistics"."count"一部分。我还尝试将 FROM 添加到更新子句,但得到了ERROR: syntax error at or near "FROM". 有没有办法让 INSERT ON CONFLICT UPDATE 与 CTE 一起工作?

Vao*_*sun 7

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.

thus try:

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"
Run Code Online (Sandbox Code Playgroud)