简体   繁体   English

Postgresql INSERT ON CONFLICT 语法

[英]Postgresql INSERT ON CONFLICT syntax

Greetings with the following test table:问候以下测试表:

CREATE TEMP SEQUENCE pid start 10000;
SELECT nextval ('pid');

CREATE TEMP TABLE project_test (
  id int DEFAULT nextval('pid') primary key,
  project_id int UNIQUE NOT NULL
    );

I am attempting to make a statement that either inserts a new value for project_id returning the id or returns the id if the project_id exists.我试图发表一个声明,要么为返回 id 的 project_id 插入一个新值,要么在 project_id 存在时返回 id。

I have attempted the following:我尝试了以下方法:

INSERT INTO project_test(project_id) VALUES(50) RETURNING id 
ON CONFLICT (project_id) DO UPDATE project_test SET project_id = 50 WHERE project_id = 50 RETURNING id;

I have read the documentation here: https://www.postgresql.org/docs/13/sql-insert.html I am on Postgres 13我已阅读此处的文档: https : //www.postgresql.org/docs/13/sql-insert.html我在 Postgres 13

I am getting a syntax error我收到语法错误

ERROR: syntax error at or near "ON"错误:“ON”处或附近的语法错误

Thanks in advance for any tips提前感谢您的任何提示

INSERT INTO project_test(project_id) VALUES(50)
ON CONFLICT (project_id) DO UPDATE SET project_id = 50 WHERE project_test.project_id = 50 RETURNING id;

The problem was the RETURNING id needs to go at the end, and then it thought column reference "project_id" was ambiguous, which is odd.问题是 RETURNING id 需要放在最后,然后它认为列引用“project_id”不明确,这很奇怪。 Thanks all谢谢大家

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

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