在PostgreSQL中with子句之后如何使用删除子句?

问题描述

查询1:

with table1 as (select * from table2) delete * from table1;

查询2:

with table1 as (select * from table2) delete * from table1 where col1 = 'something';

以上两个查询在执行后都返回错误?有人可以帮我吗?

解决方法

根据评论部分的问题说明,您可以使用下面的查询删除重复项

delete from rohilla a using rohilla b where a=b and a.ctid < b.ctid;

使用with子句,您可以执行以下操作删除重复项。 (如果整个行重复,则下面的Col1可以是任何列)

WITH x AS 
( 
         SELECT   col1,Min(ctid) AS min 
         FROM     rohilla 
         GROUP BY col1
         HAVING   Count(col1) > 1 ) 
DELETE 
FROM   rohilla b 
using  x 
WHERE  x.col1 = b.col1
AND    x.min <> b.ctid;
,

您无法从Postgres中的CTE中删除。显然,我确定您知道您可以这样做:

delete from table2
    where col1 = 'something';

如果要涉及CTE,则可以使用某种过滤,通常在主键上使用:

with table1 as (
      select * from table2
     )
delete from table2 t2 using
     table1 t1
     where t1.<primary key> = t2.<primary key> and
           t1.col1 = 'something';