Postgres查询返回SQL错误语法错误“Where”

时间:2017-01-25 02:04:33

标签: sql postgresql

我有以下查询,当我执行它时,我收到错误

INSERT INTO AM_EVENT_STATUS (EVENT_STATUS_ID, EVENT_ID, TIMESTAMP,OLD_STATUS_ID, NEW_STATUS_ID, NOTE, USERNAME)
SELECT
"external_id" AS EVENT_STATUS_ID,
"external_id" AS EVENT_ID,
"timestamp"   AS TIMESTAMP,
NULL          AS OLD_STATUS_ID,
'unknown'     AS NEW_STATUS_ID,
NULL          AS NOTE,
NULL          AS USERNAME
FROM (SELECT "2cba77463c899fee1656b367e39892"
  FROM "2cba77463c899fee1656b367e39892"
  INNER JOIN (SELECT "external_id", MAX("timestamp") AS "timestamp"
            FROM "2cba77463c899fee1656b367e39892"
              GROUP BY "external_id") LATEST WHERE "2cba77463c899fee1656b367e39892"."external_id" = LATEST."external_id"
    AND "2cba77463c899fee1656b367e39892"."timestamp" = LATEST."timestamp"
    AND "2cba77463c899fee1656b367e39892"."event_type" = 'transaction_update');

错误是:

  

SQL错误[42601]:错误:“WHERE”处或附近的语法错误位置:   601 org.postgresql.util.PSQLException:错误:或者语法错误   靠近“WHERE”位置:601

我在这里做错了什么?提前谢谢。

2 个答案:

答案 0 :(得分:2)

LATEST WHERE更改为LATEST ON。您有一个JOIN,因此正确的比较条款为ON,而不是WHERE

在最后一个括号后面还需要一个表别名。

答案 1 :(得分:0)

INSERT INTO "AM_EVENT_STATUS" ("EVENT_STATUS_ID", "EVENT_ID","TIMESTAMP", "OLD_STATUS_ID", "NEW_STATUS_ID", "NOTE", "USERNAME")
SELECT
"external_id" AS EVENT_STATUS_ID,
"external_id" AS EVENT_ID,
"timestamp"   AS TIMESTAMP,
NULL          AS OLD_STATUS_ID,
'unknown'     AS NEW_STATUS_ID,
NULL          AS NOTE,
NULL          AS USERNAME
FROM (SELECT "2cba77463c899fee1656b367e39892".*
    FROM "2cba77463c899fee1656b367e39892"
    INNER JOIN (SELECT "external_id", MAX("timestamp") AS "timestamp"
                FROM "2cba77463c899fee1656b367e39892"
                GROUP BY "external_id") AS LATEST 
    ON "2cba77463c899fee1656b367e39892"."external_id" = LATEST."external_id"
    AND "2cba77463c899fee1656b367e39892"."timestamp" = LATEST."timestamp"
    AND "2cba77463c899fee1656b367e39892"."event_type" = 'transaction_update') as EVENTSTATUS;