如何检索重复记录并在表A中删除它们,还将这些检索到的重复记录插入另一个表B(在postgres db中)
我的项目需要SQL查询。
答案 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;