Find rows with multiple duplicate fields with Active Record, Rails & Postgres

前端 未结 5 1035
有刺的猬
有刺的猬 2020-12-04 06:07

What is the best way to find records with duplicate values across multiple columns using Postgres, and Activerecord?

I found this solution here:

User.f

5条回答
  •  生来不讨喜
    2020-12-04 06:58

    Get all duplicates with a single query if you use PostgreSQL:

    def duplicated_users
      duplicated_ids = User
        .group(:first, :email)
        .having("COUNT(*) > 1")
        .select('unnest((array_agg("id"))[2:])')
    
      User.where(id: duplicated_ids)
    end
    
    irb> duplicated_users
    

提交回复
热议问题