【问题标题】:Rails use SQL group_byRails 使用 SQL group_by
【发布时间】:2016-08-10 02:10:57
【问题描述】:

我接到了模特电话Answer,这是它的表格

id      group_id    qset_id 
1       123            1
2       123            2
3       123            1
4       456            1
5       456            1
6       456            3

我需要返回arrayjson 格式,包括每个group_id 及其不同的qset_id

可能是这样的

class: [
    {
        "group_id": 123
        "qset_id": [1,2]
    },
    {
        "group_id": 456
        "qset_id": [1,3]
    }
]

我想过group_by,但我被困在这里。而且表很大,有没有一种高效的 Rails 方法来处理它?

【问题讨论】:

    标签: mysql sql ruby-on-rails json activerecord


    【解决方案1】:

    你试过了吗?

    @answer = Answer.all.group_by(&:group_id) 
    
    @answer.each_with_index do |answer, index|
      {
       'group_id': index,
       'qset_id: answer.flatten.map{|x| x_id}
      }    
    end
    

    I have to tell that I had to study more query sql to find this solution
    
    ActiveRecord::Base.connection.exec_query('SELECT group_id, GROUP_CONCAT(qset_id) FROM answers GROUP BY group_id').rows.to_h
    

    我在这里为此创建了一个测试,我收到了正确的答案。

    4.1.15@2.2.0 (main)> ActiveRecord::Base.connection.exec_query('SELECT proposal_id, GROUP_CONCAT(DISTINCT unit_id) FROM bookings GROUP BY proposal_id').rows.to_h
      SQL (0.2ms)  SELECT proposal_id, GROUP_CONCAT(DISTINCT unit_id) FROM bookings GROUP BY proposal_id
    => {1=>"2,3", 3=>"4", 4=>"5", 5=>"6"}
    

    【讨论】:

    • 我不确定,因为花了很长时间,结果没有显示。 Answer 非常庞大(超过 1000 万条记录)
    • 所以需要直接在sql中做这个动作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多