Ruby on rails rails选择具有重复项的记录

Ruby on rails rails选择具有重复项的记录,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,对于我的情况,我想从表中选择所有重复的记录 比如说 table1 id | name | sub_name 1 | joe | j1 2 | tim | t1 3 | ben | b1 4 | joe | j2 5 | tim | t2 我想选择 [#<table1 id: 1, name: "joe", sub_name: "j1">, #<table1 id: 4, name: "joe", sub_name: "j2"&g

对于我的情况,我想从表中选择所有重复的记录

比如说

table1 

id | name | sub_name

1  | joe  | j1
2  | tim  | t1 
3  | ben  | b1    
4  | joe  | j2    
5  | tim  | t2 
我想选择

 [#<table1 id: 1, name: "joe", sub_name: "j1">, #<table1 id: 4, name: "joe", sub_name: "j2">, #<table1 id: 2, name: "tim", sub_name: "t1">, #<table1 id: 5, name: "tim", sub_name: "t2">]

 and then display

 joe
  - j1
  - j2
 tim
  - t1
  - t2
有谁能帮我用AR或SQL来做这件事吗

我尝试了这个查询Table1.group:name.havingcount*>1

但结果是

[,]

或result.count返回


{[joe]=>2[tim]=>2}

我不知道这是不是最有效的方法,但你可以:

names_with_multiple_rows = Table1.group(:name).having("count(*) > 1")
res = names_with_multiple_rows.inject({}) do |h, m|
  h[m.name] = Table1.select(:sub_name).where(name: m.name)
  h
end

现在res是一个散列,其中键是名称,值是子名称。

谢谢你,Erez,你的答案很好。可能有更清晰的解决方案,但我不知道。