我有一张包含以下列的表格:
id
app_id
tag_id
created_at
updated_at
app_id
和tag_id
对应该是uniq。如何根据updated_at
列删除最旧的重复记录以确定“最旧”并配对(app_id, tag_id)
以确定“重复”?
答案 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
替换为您的实际表名。