一,创建测试表并插入数据
create table aaa(id bigserial,col1 varchar(255));
insert into aaa values(1,'b'),(2,'a'),(3,'b'),(4,'c');
select * from aaa;
二,找到重复行并删除
方法1:ctid表示数据行在它所处的表内的物理位置,ctid由两个数字组成,第一个数字表示物理块号,第二个数字表示在物理块中的行号。
select * from aaa where ctid not in(select max(ctid) from aaa group by col1);
删除重复行
delete from aaa where ctid not in(select max(ctid) from aaa group by col1);
方法2:利用exists
找到重复行
select * from aaa t1 where exists (select 1 from aaa t2 where t1.col1=t2.col1 and t1.id<t2.id )----exists后的意思是同一列相等,但是自增id不相等且id小的那一个
删除重复行
delete from aaa t1 where exists (select 1 from aaa t2 where t1.col1=t2.col1 and t1.id<t2.id )