0

CTE의 행을 삽입 (또는 충돌시 업데이트)하려고하지만이를위한 올바른 구문을 찾기 위해 고심하고 있습니다. (명확성을 위해 단순화 된) 나는이 같은 모습에 삽입하고있어 테이블은 postgresql 9.5에서 WITH 쿼리로 INSERT ON CONFLICT UPDATE가 가능합니까?

 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와 함께 사용할 수 있습니까? ON CONFLICT DO UPDATE에서

+1

어쩌면 당신은'사용해야 excluded.count' .. 당신이 반복 샌드 박스를 공유하시기 바랍니다 것입니다 .. –

+0

@VaoTsun 덕분 사용 "제외"테이블 이름은 작품으로? 벌금 – fourslashw

답변

2

https://www.postgresql.org/docs/9.5/static/sql-insert.html

SETWHERE 절은 테이블의 이름 (또는 별명)를 사용하여 기존 행에 액세스 할 수, 행에 특별한 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" 
관련 문제