ActiveRecord - 如何仅使用JOINS,GROUP和SELECT某些列?

时间:2015-12-26 21:58:28

标签: ruby-on-rails select join activerecord group-by

如果我运行以下查询,

  @top_companies               = Shipment.joins(:company)
                                        .where('...')
                                        .group('companie.name')
                                        .order('count_all DESC').limit(10).count

输出位于公司名称=>发货数量格式:

"Company name"=>12, ...}

但我还需要从companies表中获取其他列,例如id等等,所以我尝试了:

  @top_companies               = Shipment.joins(:company)
                                        .select('shipments.*, companies.id, companies.name, companies.name_slug')
                                        .where('...')
                                        .group('companie.name')
                                        .order('count_all DESC').limit(10).count

但输出仍然相同 - 为什么?如何将另一列添加到输出哈希?

3 个答案:

答案 0 :(得分:1)

您只需将Companies列添加到group语句:

即可
  @top_companies = Shipment.joins(:company)
                     .where('...')
                     .group('companies.id, companies.name, companies.name_slug')
                     .order(count_all: :desc).limit(10).count

由于您要对Shipments进行分组,如果您希望包含其中的列,则需要告诉SQL您希望如何聚合数据:

@top_companies = Shipment.joins(:company)
                   .where('...')
                   .select('AVG(shipments.delivered_in), COUNT(*), companies.id, companies.name, companies.name_slug')
                   .group('companies.id, companies.name, companies.name_slug')

答案 1 :(得分:1)

您需要在Company对象上相应地查询名称和name_slug,如下所示:

@top_companies = Shipment.joins(:company)
                .select('count(*) as shipments_count, companies.id as company_id, companies.name as company_name, companies.name_slug as company_name_slug')
                .where('...')
                .group('companie.name')
                .order('count_all DESC').limit(10)

@top_companies.map(&:shipments_count)
# this will return the shipment count 

@top_companies.map(&:company_name_slug)
# this will return the company name slug corresponding to each group of shipment by company name

您现在需要使用@top_companies.map并在map内编写任何逻辑以获得所需的输出。

答案 2 :(得分:-2)

尝试使用pluck而不是select。

Client.where(active: true).pluck(:id)
# SELECT id FROM clients WHERE active = 1
# => [1, 2, 3]

Client.distinct.pluck(:role)
# SELECT DISTINCT role FROM clients
# => ['admin', 'member', 'guest']

Client.pluck(:id, :name)
# SELECT clients.id, clients.name FROM clients
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]

http://guides.rubyonrails.org/active_record_querying.html#pluck