带有 ON CONFLICT DO UPDATE 条件的 INSERT INTO 后,PostgreSQL“输入末尾出现语法错误”

PostgreSQL “syntax error at end of input” after INSERT INTO with ON CONFLICT DO UPDATE condition

我正在尝试在我的 PostgreSQL 数据库上编写 UPSERT 代码。

使用

NamedParameterJdbcTemplate

我收到以下错误消息:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [


INSERT INTO MY_TABLE
(ID,DATE_TIMESTAMP,ENVIRONMENT,REGION,ORGANIZATION,ARRIVAL_TIMESTAMP,LAST_UPDATED) 
VALUES (?,?,?,?,?,?,?) 
ON CONFLICT (ID, DATE_TIMESTAMP, ENVIRONMENT, REGION)
DO UPDATE

]; nested exception is org.postgresql.util.PSQLException: ERROR: syntax error at end of input] with the root cause

org.postgresql.util.PSQLException: ERROR: syntax error at end of input

查询:

INSERT INTO MY_TABLE
(ID,DATE_TIMESTAMP,ENVIRONMENT,REGION,ORGANIZATION,ARRIVAL_TIMESTAMP,LAST_UPDATED) 
VALUES (:ID,:DATE_TIMESTAMP,:ENVIRONMENT,:REGION,:ORGANIZATION,:ARRIVAL_TIMESTAMP,:LAST_UPDATED) 
ON CONFLICT (ID, DATE_TIMESTAMP, ENVIRONMENT, REGION)
DO UPDATE

我试过没有冲突条件,效果很好。

我试过添加 SET 命令,但没有用。

我也试过在 DO UPDATE SET 语句之后使用 setter 我也尝试过您的解决方案,使用 EXCLUDED.COLUMN_NAME

为我要更新的每一列添加一个 SET 语句

我收到以下错误消息:

ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification  Call getNextException to see other errors in the batch.

有什么解决方法的建议吗?

我找到了解决办法。

错误的原因是我选择的约束。

CONFLICT 条件必须是 CONSTRAINT。比如主键。

在此处查看完整文档:https://www.postgresql.org/docs/9.5/sql-insert.html

ON CONFLICT can be used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. (See ON CONFLICT Clause below.)