查找任意三个常见属性的重复记录

5
在我的RoR项目中,有一个名为Customer的模型,拥有10个属性。现在我想查找那些至少有任意三个共同属性的客户。如何有效地进行这个查询?
可能的解决方案如下:
Customer.select([:first_name,:last_name,:language]).
         group(:first_name,:last_name,:language).having("count(*) > 1")

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

谢谢!提前致谢。


不,这是一个不同的问题。上面的情况是我们确切地知道这两列匹配。这个问题是询问任意三列中是否有任意两列匹配。 - Taryn East
@Taryn East:不幸的是,这个解决方案并没有解决我的问题。因为我希望那些拥有至少三个共同属性的客户。无论如何,谢谢你的评论。 - Md.Mostafizur Rahman Sahed
我根本没有提出解决方案。我投了反对票,并给出了不投票关闭为重复的原因。我的评论是针对投票关闭为重复的人,而不是针对你的 - 抱歉 - 我没有解决方案。 - Taryn East
1个回答

0

这是我目前能想到的最好方案。同时不是一个 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接