如何在postgres中执行此组ActiveRecord查询

Mar*_*tin 4 postgresql activerecord ruby-on-rails

我尝试通过3M表找到具有相同用户名的所有用户.我读到这样的东西可能会成功.

User.find(:all, :group => [:username], :having => "count(*) > 1" )
Run Code Online (Sandbox Code Playgroud)

但是因为我正在使用Postgres,所以请回复我ActiveRecord::StatementInvalid: PG::Error: ERROR: column "users.id" must appear in the GROUP BY clause or be used in an aggregate function.

我正在尝试这样的事情

User.select('users.id, users.username').having("count(*) > 1").group('users.username')
Run Code Online (Sandbox Code Playgroud)

但仍然得到同样的错误.知道我做错了什么吗?

更新:我使用它以某种方式工作User.select('users.*').group('users.id').having('count(users.username) > 1')但这个查询返回我看起来像一个空数组,即使是创建5条记录.

 GroupAggregate  (cost=9781143.40..9843673.60 rows=3126510 width=1365)
   Filter: (count(username) > 1)
   ->  Sort  (cost=9781143.40..9788959.68 rows=3126510 width=1365)
         Sort Key: id
         ->  Seq Scan on users  (cost=0.00..146751.10 rows=3126510 width=1365)
(5 rows)

 => [] 
Run Code Online (Sandbox Code Playgroud)

知道为什么会这样,以及如何获得这5行?

Mik*_*del 5

我认为你能得到的最好的方法是获取重复记录的用户名.这可以通过实现

User.select(:username).group(:username).having('COUNT(username) > 1')
Run Code Online (Sandbox Code Playgroud)