DELETE查询的Postgres语法错误

时间:2016-08-25 21:09:51

标签: python postgresql amazon-redshift psycopg2

我已使用DataGrip直接针对指定的表格成功运行此查询作为SELECT,但当我尝试将其作为DELETE运行时,它会导致语法错误。

代码:

conn = psycopg2.connect(connection_str.format(*connection_args))

with conn, conn.cursor() as curs:
    delete_duplicates_command = """
            DELETE FROM (SELECT *, row_number() OVER (PARTITION BY {pk} 
                ORDER BY _ts DESC) as row_num
            FROM {table}) as t
            WHERE t.row_num != 1;
        """.format(table=target_table, pk=primary_key)

    curs.execute(delete_duplicates_command)

错误:

Migration failed: syntax error at or near "("
    LINE 2:             DELETE FROM (SELECT *, row_number() OVER (PARTIT...
                                    ^

表和主键都是有效的字符串值。我尝试过多种方式重新格式化这个命令无法实现。

仅供参考我使用psycopg2==2.6Python 2.7.3

尝试重写查询以避免在delete中执行select:

WITH ordered_table AS
    (SELECT *, row_number() OVER (PARTITION BY pk ORDER BY _ts DESC) as row_num
        FROM orig_table)
DELETE FROM orig_table
USING ordered_table
WHERE ordered_table.row_num > 1;

导致以下错误: ERROR: syntax error at or near "DELETE"

0 个答案:

没有答案