删除基于多列的重复记录?(Remove duplicate records based on multiple columns?)

编程入门 行业动态 更新时间:2024-10-28 03:33:41
删除基于多列的重复记录?(Remove duplicate records based on multiple columns?)

我使用Heroku托管我的Ruby on Rails应用程序,由于某种原因,我可能会有一些重复的行。

有没有办法删除基于2个或更多条件的重复记录,但只保留该重复集合的1个记录?

在我的用例中,我的数据库中有汽车的Make和Model关系。

Make Model --- --- Name Name Year Trim MakeId

我想删除所有具有相同名称,年份和修剪的模型记录,但保留1个记录(意思是,我需要记录,但只有一次)。 我使用Heroku控制台,所以我可以轻松地运行一些活动的记录查询。

有什么建议么?

I'm using Heroku to host my Ruby on Rails application and for one reason or another, I may have some duplicate rows.

Is there a way to delete duplicate records based on 2 or more criteria but keep just 1 record of that duplicate collection?

In my use case, I have a Make and Model relationship for cars in my database.

Make Model --- --- Name Name Year Trim MakeId

I'd like to delete all Model records that have the same Name, Year and Trim but keep 1 of those records (meaning, I need the record but only once). I'm using Heroku console so I can run some active record queries easily.

Any suggestions?

最满意答案

class Model def self.dedupe # find all models and group them on keys which should be common grouped = all.group_by{|model| [model.name,model.year,model.trim,model.make_id] } grouped.values.each do |duplicates| # the first one we want to keep right? first_one = duplicates.shift # or pop for last one # if there are any more left, they are duplicates # so delete all of them duplicates.each{|double| double.destroy} # duplicates can now be destroyed end end end Model.dedupe 查找全部 将它们分组在您需要的唯一性的键上 循环分组模型的哈希值 删除第一个值,因为您要保留一个副本 删除其余的 class Model def self.dedupe # find all models and group them on keys which should be common grouped = all.group_by{|model| [model.name,model.year,model.trim,model.make_id] } grouped.values.each do |duplicates| # the first one we want to keep right? first_one = duplicates.shift # or pop for last one # if there are any more left, they are duplicates # so delete all of them duplicates.each{|double| double.destroy} # duplicates can now be destroyed end end end Model.dedupe Find All Group them on keys which you need for uniqueness Loop on the grouped model's values of the hash remove the first value because you want to retain one copy delete the rest

更多推荐

本文发布于:2023-07-30 13:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1337867.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:records   duplicate   Remove   columns   multiple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!