如何在 table A 中检索重复记录并删除它们,同时将这些重复记录插入另一个 table B(在 postgres 中)
How to retrieve duplicate records and delete them in table A, also insert these duplicate records in another table B (in postgres)
如何在 table A 中检索重复记录并删除它们,并将这些检索到的重复记录插入另一个 table B(在 postgres 数据库中)
SQL 我的项目需要查询。
要在没有唯一列的情况下删除重复项,您可以使用 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
子句获取删除的行并将它们插入到其他 table:
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;
如何在 table A 中检索重复记录并删除它们,并将这些检索到的重复记录插入另一个 table B(在 postgres 数据库中)
SQL 我的项目需要查询。
要在没有唯一列的情况下删除重复项,您可以使用 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
子句获取删除的行并将它们插入到其他 table:
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;