PostgreSql:不能在UPDATE中使用聚合函数

时间:2014-10-07 13:30:08

标签: postgresql sql-update aggregate-functions

我有一个Oracle移植到PostgreSql的查询:

UPDATE "SPD_PG"."TT_SPLDR_11A2F324_29" 
SET "SECT_ORDER" = MAX("SECTIONS"."SECT_ORDER")+1 FROM "SPD_PG"."SECTIONS"
INNER JOIN "SPD_PG"."META_SECTIONS" ON ("SECTIONS"."META_SECT_ID"="META_SECTIONS"."META_SECT_ID")
WHERE ("META_SECTIONS"."META_SECT_ORDER"="TT_SPLDR_11A2F324_29"."META_SECT_ORDER"-1)
AND ("SECTIONS"."DOC_ID"="TT_SPLDR_11A2F324_29"."DOC_ID")
AND ("TT_SPLDR_11A2F324_29"."META_SECT_ORDER">0)

这给了我:ERROR: cannot use aggregate function in UPDATE,似乎PostgreSql在Update语句中不支持MAX

但是,如果我按如下方式重写查询:

UPDATE "SPD_PG"."TT_SPLDR_11A2F324_29" 
SET "SECT_ORDER" = "MAX_VALUE" FROM (
  SELECT MAX("SECTIONS"."SECT_ORDER")+1 AS "MAX_VALUE" FROM "SPD_PG"."SECTIONS"
  INNER JOIN "SPD_PG"."META_SECTIONS" ON ("SECTIONS"."META_SECT_ID"="META_SECTIONS"."META_SECT_ID")
  WHERE ("META_SECTIONS"."META_SECT_ORDER"="TT_SPLDR_11A2F324_29"."META_SECT_ORDER"-1)
  AND ("SECTIONS"."DOC_ID"="TT_SPLDR_11A2F324_29"."DOC_ID")
  AND ("TT_SPLDR_11A2F324_29"."META_SECT_ORDER">0)
) "TBL_ALIAS"

它说ERROR: subquery in FROM cannot refer to other relations of same query level

所以我无法弄清楚如何编写此查询。

1 个答案:

答案 0 :(得分:1)

试试这个:

UPDATE "SPD_PG"."TT_SPLDR_11A2F324_29" 
   SET "SECT_ORDER" = (SELECT MAX("SECTIONS"."SECT_ORDER")+1 
                         FROM "SPD_PG"."SECTIONS"
                        INNER JOIN "SPD_PG"."META_SECTIONS" ON ("SECTIONS"."META_SECT_ID"="META_SECTIONS"."META_SECT_ID")
                        WHERE ("META_SECTIONS"."META_SECT_ORDER"="TT_SPLDR_11A2F324_29"."META_SECT_ORDER"-1)
                          AND ("SECTIONS"."DOC_ID"="TT_SPLDR_11A2F324_29"."DOC_ID")
                          AND ("TT_SPLDR_11A2F324_29"."META_SECT_ORDER">0)
                      )