【问题标题】:How to use delete clause after with clause in postgresql?如何在 postgresql 中的 with 子句之后使用 delete 子句?
【发布时间】:2021-01-31 17:07:03
【问题描述】:

查询 1:

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

查询 2:

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

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

【问题讨论】:

  • 您不能从查询结果中删除。查询 1 可以替换为 delete from table2,查询 2 可以替换为 delete from table2 where col1 = 'something' - 但我认为这不是您实际的潜在问题。你到底想做什么?请提供一些样本数据和预期结果
  • 我正在尝试使用 row_number 删除重复的行,如下所示:with rohilla as (select row_number() over(partition by fruit order by fruit) row_num, fruit from rk) delete from rohilla where row_num >1 ;
  • 问题是我的桌子上没有标识符,所以你可以为此发布 sol

标签: sql postgresql duplicates sql-delete


【解决方案1】:

根据评论区的问题陈述,可以使用下面的查询删除重复项

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;

【讨论】:

    【解决方案2】:

    您不能从 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';
    

    【讨论】:

    • CTE 是什么意思?
    • @RahulKumar 。 . . “公用表表达式”。
    猜你喜欢
    • 2016-09-10
    • 2018-10-26
    • 2018-08-23
    • 1970-01-01
    • 2020-04-28
    • 2021-05-05
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多