根据列对删除重复记录?

时间:2015-05-12 06:43:55

标签: ruby postgresql ruby-on-rails-4 activerecord

我有一张包含以下列的表格:

id
app_id
tag_id
created_at
updated_at

app_idtag_id对应该是uniq。如何根据updated_at列删除最旧的重复记录以确定“最旧”并配对(app_id, tag_id)以确定“重复”?

1 个答案:

答案 0 :(得分:2)

 ActiveRecord::Base.connection.execute <<-SQL
   delete from my_table where id in (
     select t1.id
     from my_table t1
     inner join (
       select app_id, tag_id, min(updated_at) as oldest
       from my_table
       group by app_id, tag_id
     ) t2 
     on t1.app_id = t2.app_id 
     and t1.tag_id = t2.tag_id
     and t1.updated_at = t2.oldest
   )
 SQL

my_table替换为您的实际表名。