"CONSTRAINT" 处或附近的语法错误 PostgreSQL

Syntax Error at or near "CONSTRAINT" PostgreSQL

我正在尝试创建一个新的 table 并在下面的语句中不断得到一个 syntax error at or near "CONSTRAINT"。我已经确保在我声明的最后一列之后有一个 ,,它位于 CONSTRAINT 行的正上方 Tags。有谁知道为什么会这样?声明约束的所有在线示例似乎都涉及 CREATE TABLE 语句,而不是 CREATE TABLE AS 语句。那有关系吗?感谢您的帮助!

顺便说一句,下面的约束线是 copied/pasted 来自我已经创建的 table,它使用了 CREATE TABLE 语句,而不是 CREATE TABLE AS 语句,这就是为什么我问约束是否不适用于 CREATE TABLE AS 语句。

CREATE TABLE "2017Projects" AS
SELECT
    "STAGING_PROJECTS"."_PROJECT_NUMBER", 
    "STAGING_PROJECTS"."_PROJECT_DESCRIPTION",
    "STAGING_PROJECTS"."_PROJECT_STATUS",
    "STAGING_PROJECTS"."_TEMPLATE_FLAG",
    "STAGING_PROJECTS"."_PROJECT_START_DATE",
    "STAGING_PROJECTS"."_PROJECT_COMPLETION_DATE",
    "STAGING_PROJECTS"."_COMPANY",
    "STAGING_PROJECTS"."_LOCATION_NUMBER",
    "STAGING_TASKS"."_PARENT_TASK_NUMBER",
    "STAGING_TASKS"."_PARENT_TASK_DESCRIPTION",
    "STAGING_TASKS"."_TASK_NUMBER",
    "STAGING_TASKS"."_TASK_DESCRIPTION",
    "STAGING_TASKS"."_TASK_START_DATE",
    "STAGING_TASKS"."_TASK_COMPLETION_DATE",
    "STAGING_TASKS"."_EBS_ACCOUNT",
    "STAGING_TASKS"."_FUSION_ACCOUNT",
    CASE
        WHEN left("STAGING_PROJECTS"."_PROJECT_NUMBER",2) = 'C0' THEN 
            '('||"STAGING_PROJECTS"."_PROJECT_NUMBER"||') '||"STAGING_PROJECTS"."_PROJECT_DESCRIPTION"
        ELSE
            "STAGING_PROJECTS"."_PROJECT_DESCRIPTION"
    END AS "Project",
    '('||"STAGING_TASKS"."_TASK_NUMBER"||') '||"STAGING_TASKS"."_TASK_DESCRIPTION" AS "Task",
    NULL AS "Investment_Priority",
    NULL AS "Class",
    NULL AS "Tags",

    --ERROR ON NEXT LINE HERE!!!
    CONSTRAINT "2017Projects_pk" PRIMARY KEY ("_PROJECT_NUMBER", "_TASK_NUMBER")
FROM
    "STAGING_PROJECTS";

您需要使用第二条语句添加约束:

CREATE TABLE "2017Projects" AS
SELECT
    "STAGING_PROJECTS"."_PROJECT_NUMBER", 
    ...,
    NULL AS "Tags"
FROM
    "STAGING_PROJECTS";

ALTER TABLE "2017Projects" ADD CONSTRAINT "2017Projects_pk"
    PRIMARY KEY ("_PROJECT_NUMBER", "_TASK_NUMBER")

CREATE TABLEALTER TABLE 语句应在单个事务中 运行。

请浏览 this great Stack DBA article,@a_horse_with_no_name 作为贡献者。