2016-11-13 99 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 *