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

前端 未结 5 1014
有刺的猬
有刺的猬 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:57

    Tested & Working Version

    User.select(:first,:email).group(:first,:email).having("count(*) > 1")
    

    Also, this is a little unrelated but handy. If you want to see how times each combination was found, put .size at the end:

    User.select(:first,:email).group(:first,:email).having("count(*) > 1").size
    

    and you'll get a result set back that looks like this:

    {[nil, nil]=>512,
     ["Joe", "test@test.com"]=>23,
     ["Jim", "email2@gmail.com"]=>36,
     ["John", "email3@gmail.com"]=>21}
    

    Thought that was pretty cool and hadn't seen it before.

    Credit to Taryn, this is just a tweaked version of her answer.

提交回复
热议问题