PostgreSQL删除重复项

Uas*_*ana 6 postgresql

我正在研究postgres查询以从表中删除重复项.下表是动态生成的,我想编写一个select查询,如果第一行有重复值,它将删除记录.

该表看起来像这样

Ist col  2nd col
 4        62
 6        34
 5        26
 5        12
Run Code Online (Sandbox Code Playgroud)

我想写一个select查询,删除第3行或第4行.

小智 9

不需要中间表:

delete from df1
where ctid not in (select min(ctid)
                   from df1
                   group by first_column);
Run Code Online (Sandbox Code Playgroud)

如果要从大型表中删除许多行,则使用中间表的方法可能会更快。


如果您只想获取一列的唯一值,您可以使用:

select distinct on (first_column) *
from the_table
order by first_column;
Run Code Online (Sandbox Code Playgroud)

或者简单地

select first_column, min(second_column)
from the_table
group by first_column;
Run Code Online (Sandbox Code Playgroud)