【问题标题】:Find Duplicated record for any 3 common attributes查找任何 3 个常见属性的重复记录
【发布时间】:2015-07-29 06:09:31
【问题描述】:

在我的 RoR 项目中,有一个具有 10 个属性的客户模型。现在我想找到那些至少具有任何三个共同属性的客户。如何有效地进行此查询?

也许这是一个解决方案:

Customer.select([:first_name,:last_name,:language]).
         group(:first_name,:last_name,:language).having("count(*) > 1")

但是这个解决方案需要太多的组合来检查。请帮助提供更好的解决方案。

谢谢!提前。

【问题讨论】:

  • 不,这是一个不同的问题。以上是我们确切知道这两个给定列匹配的地方。这个问题询问是否有三分之二的可能列匹配
  • @Taryn East:不幸的是,这个解决方案不能解决我的问题。因为我希望那些至少具有任何三个共同属性的客户。无论如何,谢谢您的评论。
  • 我根本没有提出解决方案。我投票反对关闭,并给出了不重复投票关闭的理由。我的评论是针对投票关闭为重复的人,而不是针对您-抱歉-我没有解决方案。

标签: sql ruby-on-rails ruby rails-activerecord


【解决方案1】:

这是迄今为止我能想到的最好的。也不是 SQL 解决方案。

# Arrange a 3-items combination of columns, removed id and timestamps
triplets = Customer.column_names.reject {|column| column == "id" || column == "created_at" || column == "updated_at"}.combination(3).to_a

#Group All records by same item values for each 3-items combination
all = Customer.all
res = triplets.map do|t| 
  all.to_a.group_by {|c| [ {t[0] => c.send(t[0].to_sym)}, { t[1] => c.send(t[1].to_sym) }, {t[2] => c.send(t[2].to_sym)} ]} 
end  
# removed combinations with only 1 record
final_result = res.map {|h1| h1.reject { |k, v| v.count <= 1}}

# There you have customer with 3 attributes common combinations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2019-09-24
    • 2016-07-03
    • 2019-02-16
    • 1970-01-01
    • 2014-03-18
    • 2015-02-14
    相关资源
    最近更新 更多