如何使用Active Record查找具有重复数据的记录

srb*_*ert 27 ruby activerecord arel

使用ruby和新的Activerecord在列中查找具有重复值的记录的最佳方法是什么?

fl0*_*00r 50

将@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")
Run Code Online (Sandbox Code Playgroud)

  • 这段代码是否也适用于PostgreSQL?它返回错误"PGError:ERROR:column"数量"不存在" (7认同)
  • @Marc,我不确定.但你可以尝试`Type.select("id,count(id)as quantity").group(:name).having("count(id)> 1")` (5认同)
  • @holaSenor - 究竟是什么是非精确复制品?(双关语) (3认同)

bro*_*okr 24

以下是我使用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} }
Run Code Online (Sandbox Code Playgroud)

真的,这只是编写SQL的一种更好的方法.这将查找具有重复last_name值的所有记录,并告诉您在一个漂亮的哈希中有多少以及姓氏是多少.

  • 是的,这也适用于postgres.优雅.谢谢! (2认同)

Sam*_*Sam 16

我用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}
Run Code Online (Sandbox Code Playgroud)

  • 这正是我所需要的 (3认同)

Tut*_*teC 11

使用自定义SQL,它会找到types相同的值name:

sql = 'SELECT id, COUNT(id) as quantity FROM types
         GROUP BY name HAVING quantity > 1'
repeated = ActiveRecord::Base.connection.execute(sql)
Run Code Online (Sandbox Code Playgroud)


sim*_*rmy 5

在Rails 2.x中,select是AR类的私有方法.只需使用find():

klass.find(:all, 
  :select => "id, count(the_col) as num", 
  :conditions => ["extra conditions here"], 
  :group => 'the_col', 
  :having => "num > 1")
Run Code Online (Sandbox Code Playgroud)

  • 这里完全偏离主题,严肃挖掘评论......但为什么它比SQL更好? (3认同)