使用WITH查询在INSERT INTO ON CONFLICT中使用时遇到的问题

时间:2018-10-25 11:09:28

标签: java postgresql jdbc postgresql-10

我将查询从Oracle数据库更改为PostgreSQL,在此查询中出现此错误:

 ERROR: syntax error at or near "ON"

查询是:

WITH d as (
      SELECT ? AS summary, ? AS eventTime), ai as (select * from alarm)
ON (ai.fault_id=? AND ai.external_key=?)
INSERT INTO alarm AS ai(
     alarm_id,
     fault_id,
     external_key)
VALUES (nextval('seq_alrm_instnc_alrm_instnc_id'),?,?)
ON CONFLICT DO UPDATE SET
        (${buildUpdateAttributes(attributes)}
        ai.summary = d.summary,
        ai.system_last_update_time = default,
        ai.event_sequence_number =
          CASE
            WHEN (d.event_number > ai.event_number) THEN d.event_number
            ELSE ai.event_number
          END)

我正在使用JDBC连接到数据库,这是调用代码

try (PreparedStatement ps = super.prepareStatement_(sql_query)) {
    PreparedStatementHelper psh = new PreparedStatementHelper(ps);
    psh.add(attribute1);
    ...
    ps.execute()

我尝试了不同的方法,并仔细阅读了Postgres文档,找不到问题所在,也没有找到针对这种情况的答案

1 个答案:

答案 0 :(得分:1)

我不太了解您要在此处执行的操作,您以错误的方式混合了太多语法元素,这真的很难理解。

两个CTE(WITH ...)似乎完全不相关。如果您只想提供一些值并在违反UNIQUE键的情况下进行更新,则基本语法为:

insert into the_table (col_1, col_2, col_3, col_4)
values (1,2,3,4)
on conflict (col_1,col_2) do update 
  set col_3 = excluded.col_3,
      col_4 = excluded.col_4;

特殊关键字excluded用于引用导致违反唯一约束的行的VALUES子句中提供的列值。

您的CTE提供了一个参数eventTime,以后将不再使用它。假设应该是event_number,那么也许您正在寻找这样的东西:

INSERT INTO alarm 
  -- specify all columns for which you provide a value 
  (alarm_id, fault_id, external_key,summary, event_sequence_number, event_number)
VALUES 
  -- provide a value for each column
  (nextval('seq_alrm_instnc_alrm_instnc_id'), ?, ?, ?, ?, ? )
  -- define the columns of the unique constraint you want to "catch"
ON CONFLICT (fault_id, external_key) 
DO UPDATE SET
   -- "excluded.summary" refers to the corresponding value from the VALUES clause
   summary = excluded.summary, 
   system_last_update_time = default,
   -- excluded.event_number refers to the corresponding value from the VALUES clause
   event_sequence_number = CASE
                             WHEN excluded.event_number > alarm.event_number THEN excluded.event_number
                             ELSE alarm.event_number
                           END