简体   繁体   English

在PostgreSQL 9.5中可以从WITH查询插入冲突更新吗?

[英]is INSERT ON CONFLICT UPDATE from WITH query possible in postgresql 9.5?

I'm trying to insert (or update on conflict) rows from CTE but struggling to find right syntax for it. 我正在尝试从CTE插入(或在冲突时更新)行,但是努力寻找正确的语法。 The table I'm inserting in looks like this (Simplified for the sake of clarity) 我要插入的表格如下所示(为清楚起见已简化)

        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")

This is my query: 这是我的查询:

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"

which gives me ERROR: missing FROM-clause entry for table "Statistics" on SET "count" = "Statistics"."count" part. 这给我一个ERROR: missing FROM-clause entry for table "Statistics" SET "count" = "Statistics"."count"部分的ERROR: missing FROM-clause entry for table "Statistics" I also tried to add FROM to update clause but got ERROR: syntax error at or near "FROM" . 我也尝试将FROM添加到update子句,但出现ERROR: syntax error at or near "FROM" Is there a way to make INSERT ON CONFLICT UPDATE work with CTE? 有没有办法让CTE与INSERT ON CONFLICT UPDATE一起使用?

https://www.postgresql.org/docs/9.5/static/sql-insert.html 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. ON CONFLICT DO UPDATESETWHERE子句可以使用表名(或别名)访问现有行,并使用特殊的excluded表访问建议插入的行。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM