我试图从CTE插入(或更新冲突)行,但努力为它找到正确的语法。我插入的表格看起来像这样(为了清楚起见,简化了)
<div class="left">
<img class="img-responsive" src="https://vignette.wikia.nocookie.net/geosworld/images/0/09/Toon_link.jpg/revision/latest?cb=20131223183834" style="margin: auto;">
</div>
<div class="mid">
<h1>Priserna</h1>
<span class="border"></span>
<p style="text-align: center;margin-top: 15px;">Nedan hittar du alla våra tjänster vi har att erbjuda</p>
</div>
<div class="right">
<img class="img-responsive" src="https://vignette.wikia.nocookie.net/geosworld/images/0/09/Toon_link.jpg/revision/latest?cb=20131223183834" style="margin: auto;">
</div>
这是我的查询:
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"
部分给我ERROR: missing FROM-clause entry for table "Statistics"
。
我还尝试将FROM添加到update子句但得到了SET "count" = "Statistics"."count"
。有没有办法让INSERT ON CONFLICT UPDATE与CTE一起工作?
答案 0 :(得分:4)
https://www.postgresql.org/docs/9.5/static/sql-insert.html
SET
中的WHERE
和ON CONFLICT DO UPDATE
子句可以使用表名(或别名)访问现有行,并使用特殊访问建议插入的行excluded
表。
因此尝试:
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"