PostgreSQL with-delete “relation does not exists”

后端 未结 3 634
借酒劲吻你
借酒劲吻你 2020-12-15 07:55

I am using postgreSQL 9.1 and I want to delete duplicates from my table using this tip: https://stackoverflow.com/a/3822833/2239537

So, my query looks like that:

相关标签:
3条回答
  • 2020-12-15 08:27

    For me it worked Like this in Postgres/GreenPlum :

    delete
    from card where id in (
    with cte as (
        select
            id,
            row_number() over(partition by code, card_id, parent_id order by id desc) as rn
        from card
    )
    select id from cte where rn > 1);
    
    0 讨论(0)
  • 2020-12-15 08:32

    that's because CTE in PostgreSQL works differently than CTE in SQL Server. In SQL Server CTE are like an updatable views, so you can delete from them or update them, in PostgreSQL you cannot.

    you can join cte and delete, like:

    with cte as (
        select
            id,
            row_number() over(partition by code, card_id, parent_id order by id desc) as rn
        from card
    )
    delete
    from card
    where id in (select id from cte where rn > 1)
    

    On the other hand, you can write DDL statements inside CTE in PostgreSQL (see documentation) and this could be very handy. For example, you can delete all rows from card and then insert only those having row_number = 1:

    with cte1 as (
        delete
        from card
        returning *
    ), cte2 as (
        select
            row_number() over(partition by code, card_id, parent_id order by id desc) as rn,
            *
        from cte1
    )
    insert into card
    select <columns here>
    from cte2
    where rn = 1
    
    0 讨论(0)
  • 2020-12-15 08:39

    I know, you are asking how you can solve your problem using the WITH statement, and got a good answer already. But I suggest looking at alternatives in the same question you linked.

    What about this one?

    DELETE FROM card
    WHERE id NOT IN (
      SELECT MIN(id) FROM card
      GROUP BY code, card_id, parent_id 
    );
    
    0 讨论(0)
提交回复
热议问题