具有内部查询的SQL Insert语句不起作用

时间:2019-04-12 11:09:26

标签: sql database amazon-redshift

继续AWS Redshift Table Delta Load Plan's Guidance

以下查询中给出的选择效果很好,并在阶段表中返回新的插入内容:

SELECT A, B, C, D, E, F, G
      FROM TABLE_STAGE A
     WHERE NOT EXISTS (SELECT B.ID
                     FROM TABLE_FINAL B
                    WHERE B.B = A.B
                      AND B.C = A.C
                      AND B.D = A.D
                      AND B.E = A.E);

但是当我尝试使用以下语句将其插入到最终表中时,它将失败:

INSERT INTO TABLE_FINAL values
(SELECT A, B, C, D, E, F, G
  FROM TABLE_STAGE A
 WHERE NOT EXISTS (SELECT B.ID
                 FROM TABLE_FINAL B
                WHERE B.B = A.B
                  AND B.C = A.C
                  AND B.D = A.D
                  AND B.E = A.E));

查询是正确的,用于仅获取复合键是新键且在最终表中不存在的那些行。如果这不是正确的解决方案,最有效的方法是什么。怎么做?

2 个答案:

答案 0 :(得分:2)

插入时,应始终包含列列表:

INSERT INTO TABLE_FINAL (A, B, C, D, E, F, G)
    SELECT A, B, C, D, E, F, G
    FROM TABLE_STAGE A
    WHERE NOT EXISTS (SELECT B.ID
                      FROM TABLE_FINAL B
                      WHERE B.B = A.B AND
                            B.C = A.C AND
                            B.D = A.D AND
                            B.E = A.E
                     );

如果失败,则最常见的原因是列中的类型不一致。您也可能没有为没有默认值的声明为not null的列分配值。

答案 1 :(得分:1)

尝试这个:

INSERT INTO TABLE_FINAL 
SELECT A, B, C, D, E, F, G
  FROM TABLE_STAGE A
 WHERE NOT EXISTS (SELECT B.ID
                 FROM TABLE_FINAL B
                WHERE B.B = A.B
                  AND B.C = A.C
                  AND B.D = A.D
                  AND B.E = A.E);