如何检索重复记录并在表A中删除它们,也将这些重复记录插入另一个表B(在postgres中)

时间:2015-03-05 06:24:33

标签: postgresql duplicates records

如何检索重复记录并在表A中删除它们,还将这些检索到的重复记录插入另一个表B(在postgres db中)

我的项目需要SQL查询。

1 个答案:

答案 0 :(得分:0)

要删除没有唯一列的重复项,您可以使用ctid虚拟列,这与Oracle中的rowid基本相同:

delete from table_A t1
where ctid <> (select min(t2.ctid)
             from table_A t2
             where t1.unique_column = t2.unique_column);

您可以使用returning子句获取已删除的行并将其插入另一个表中:

with deleted as (
  delete from table_A x1
  where ctid <> (select min(t2.ctid)
                 from table_A t2
                 where t1.unique_column = t2.unique_column);

  returning * 
)
insert into table_B (col_1, col_2)
select unique_column, some_other_column
from deleted;

如果您还想查看这些已删除的行,您可以投入另一个CTE:

with deleted as (
  delete from table_A x1
  where ctid <> (select min(t2.ctid)
                 from table_A t2
                 where t1.unique_column = t2.unique_column);

  returning * 
), moved as (
  insert into table_B (col_1, col_2)
  select unique_column, some_other_column
  from deleted
  returning *
)
select *
from moved;