"SELECT" 或附近的 PostgreSQL 语法错误

PostgreSQL syntax error at or near "SELECT"

我不知道为什么会出现这个错误。查询工作正常,然后我尝试让它更漂亮,然后发生了这种情况

UPDATE "topTenCategories" SET "membersCount" =  "tempTable"."newVal" FROM 
    ( 
        VALUES 
        (
            SELECT count(*), "g"."id" FROM 
            "groups" AS "g" 
            LEFT JOIN 
            "groupMembers" As "gm" 
            ON "g"."id" = "gm"."groupId" 
            WHERE "g"."isCategory" is true and "g"."parentCategoryId" is null group by ("g"."id")
        )
    ) AS tempTable ("newVal", "id")
    WHERE "topTenCategories"."groupId" = "tempTable"."id";
ERROR:  syntax error at or near "SELECT"
LINE 5:                 SELECT count(*), "g"."id" FROM 
                        ^
SQL state: 42601
Character: 137

如有任何帮助,我们将不胜感激

您不能像这样将 SELECT 放入 values 子句中。 VALUES 子句用于常量值,此处不需要。

UPDATE "topTenCategories" 
    SET "membersCount" =  tempTable."newVal" 
FROM ( 
  SELECT count(*), "g"."id" 
  FROM "groups" AS "g" 
    LEFT JOIN "groupMembers" As "gm" ON "g"."id" = "gm"."groupId" 
  WHERE "g"."isCategory" is true 
    and "g"."parentCategoryId" is null group by ("g"."id")
) AS tempTable("newVal", "id")
WHERE "topTenCategories"."groupId" = tempTable."id";

您还需要在引用 temptable 时删除双引号,因为引号使其区分大小写,并且 tempTable"tempTable"

的名称不同

一般来说,recommended 避免使用那些可怕的引号标识符开头是非常重要的。