在使用 Ruby 和新的 Activerecord 中,查找列中具有重复值的记录的最佳方法是什么?
在使用 Ruby 和新的 Activerecord 中,查找列中具有重复值的记录的最佳方法是什么?
将 @TuteC 翻译成 ActiveRecord:
sql = 'SELECT id,
COUNT(id) as quantity
FROM types
GROUP BY name
HAVING quantity > 1'
#=>
Type.select("id, count(id) as quantity")
.group(:name)
.having("quantity > 1")
PGError: ERROR: column "quantity" does not exist
。 - MarcType.select("id, count(id) as quantity").group(:name).having("count(id) > 1")
。 - fl00r以下是我使用AREL助手解决它的方法,没有使用自定义SQL:
Person.select("COUNT(last_name) as total, last_name")
.group(:last_name)
.having("COUNT(last_name) > 1")
.order(:last_name)
.map{|p| {p.last_name => p.total} }
实际上,这只是一种更好的编写 SQL 语句的方式。它可以找到所有具有重复 last_name 值的记录,并以漂亮的哈希形式告诉您有多少个以及它们的姓氏是什么。
我在使用2016年的技术栈(Rails 4.2,Ruby 2.2)时遇到了一个难题,最终通过以下方法解决:
> Model.select([:thing]).group(:thing).having("count(thing) > 1").all.size
=> {"name1"=>5, "name2"=>4, "name3"=>3, "name4"=>2, "name5"=>2}
使用自定义 SQL,可以查找具有相同 name
值的 types
:
sql = 'SELECT id, COUNT(id) as quantity FROM types
GROUP BY name HAVING quantity > 1'
repeated = ActiveRecord::Base.connection.execute(sql)
klass.find(:all,
:select => "id, count(the_col) as num",
:conditions => ["extra conditions here"],
:group => 'the_col',
:having => "num > 1")
这里提供了一种解决方案,扩展了其他答案,以显示如何查找和迭代按重复字段分组的记录:
duplicate_values = Model.group(:field).having(Model.arel_table[:field].count.gt(1)).count.keys
Model.where(field: duplicate_values).group_by(&:field).each do |value, records|
puts "The records with ids #{records.map(&:id).to_sentence} have field set to #{value}"
end
看起来需要用两个查询来完成这个操作,但这个回答证实了这种方法。