2016-11-04 12 views
1

私はPostgres 9.5を使用しています。私は私のテーブル内のデータ(しかし一意のID)の同じ行を見つけるために設計された以下のクエリを持っています。Postgresで2つの重複したデータ行を削除するにはどうすればよいですか?

select e.name, 
     e.day, 
     e.distance, 
     e.created_at, 
     e2.created_at 
from events e, 
    events e2 
where e.name = e2.name 
    and e.distance = e2.distance 
    and e.day = e2.day 
    and e.web_crawler_id = e2.web_crawler_id 
    and e.id <> e2.id 
    and e.web_crawler_id = 1 
order by e.day desc; 

私は最終的に重複行の1つを削除したい - ので、おそらく最も偉大な「のcreated_at」日付で行を削除します。しかし、2つの同じ行のうちの1つだけを返すようにクエリを書く方法がわかりません。それ、どうやったら出来るの?

答えて

0

そこに多くの方法があるが、はるかにあなたのSQLを変更することなく、あなただけのIDの代わりに> <のより大きい行うことができます。

select e.name, e.day, e.distance, e.created_at, e2.created_at 
from events e, events e2 
where e.name = e2.name 
and e.distance = e2.distance 
and e.day = e2.day 
and e.web_crawler_id = e2.web_crawler_id 
and e.id > e2.id 
and e.web_crawler_id = 1 
0

あなたはLIMITを使用することができます。

select e.name, e.day, e.distance, e.created_at, e2.created_at from events e, events e2 where e.name = e2.name and e.distance = e2.distance and e.day = e2.day and e.web_crawler_id = e2.web_crawler_id and e.id <> e2.id and e.web_crawler_id = 1 order by e.day desc LIMIT 1; 
関連する問題