2016-11-13 62 views
2

这两行除了时间戳列以外都有相同的列 - created_at如何删除postgres表中两个重复条目的一行?

我只想保留其中的一行 - 无所谓哪个。

这就是我能够根据具有较小值的created_at列来选择这些重复行中每个重复行的一种。

select e.id, e.user_id, e.r_needed, e.match, e.status, e.stage, e.created_at 
    from employee e, employee e2 where e.id=e2.id and e.user_id=e2.user_id and 
    e.status = 12 and e2.status=12 and e.stage=false and e2.stage=false and 
    e.match=true and e2.match=true and e.user_id=12 and e.r_needed=true and e2.r_needed=true 
    and e.created_at<e2.created_at and DATE(e.created_at)='2015-10-08'; 

然而,想不通我怎么能删除这行,这样,无论是副本还是没有得到删除,只在上面选择的那些吗?

基本上,我想删除所有与我上面的select查询中的列匹配的行以及具有较小的created_at值的行。

我的表没有主键或唯一键。

+0

将行号与适当的分区一起使用,然后删除行号仅为1的地方。 –

+0

@TimBiegeleisen:更好地使用** row_number> 1 **而不是:) – dnoeth

+0

你可以给我举个例子吗?我可以如何在上面的查询中使用它? – Tisha

回答

1

您可以使用相关子查询代替连接:

select * from employee e 
where exists 
(select * from employee e2 
    where e.id=e2.id and e.user_id=e2.user_id 
    and e.status = 12 and e2.status=12 and e.stage=false 
    and e2.stage=false and e.match=true and e2.match=true 
    and e.user_id=12 and e.r_needed=true and e2.r_needed=true 
    and e.created_at<e2.created_at 
    and DATE(e.created_at)='2015-10-08' 
); 

如果返回重复的行正确,您可以切换到delete,而不是select *