在连接表上自定义选择

时间:2013-10-04 12:42:49

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

我正在使用rails 3.2,并尝试使用ActiveRecord来查询我的数据库。 我有2个activerecord模型,Admin和Order:

class Admin < ActiveRecord::Base
  attr_accessible :email, :name
  has_many :orders
class Order < ActiveRecord::Base
  attr_accessible :operation
  belongs_to :admin

在我的例子中,order.operation是一个字符串,表示订单类型。我正在尝试构建一个查询,给出了三列:

admin.name, admin.orders.where(:operation => 'bonus').count, admin.orders.where(:operation => 'gift').count

有没有办法让它适合单个查询?

EDITED: 这是原始的SQL来获得我需要的东西:

SELECT t_a.admin_id_com, t_a.name, gb_f_f_gb_f_fi.bonus_count, gb_f_f_gb_f_fi.gifts_count 
FROM (
  SELECT f_fil.admin_id_gifts, f_fil.gifts_count, f_filt.admin_id_bonus, f_filt.bonus_count 
  FROM (
    SELECT admin_id as admin_id_gifts, count(distinct id) as gifts_count FROM orders WHERE operation = 'new gifts!' GROUP BY admin_id_gifts) 
  f_fil LEFT OUTER JOIN (
    SELECT admin_id as admin_id_bonus, count(distinct id) as bonus_count FROM orders WHERE operation = 'new bonuses!' GROUP BY admin_id_bonus) 
  f_filt ON (f_fil.admin_id_gifts = f_filt.admin_id_bonus)) 
gb_f_f_gb_f_fi LEFT OUTER JOIN (
  SELECT id AS admin_id_com, t_ad.name FROM admins t_ad) t_a ON (gb_f_f_gb_f_fi.admin_id_gifts = t_a.admin_id_com)

是否可以使用ActiveRecord来建立查询?

1 个答案:

答案 0 :(得分:1)

试试这个:

@admins   = Admin.joins(:orders).
                 select("admins.id, admins.name, orders.id, 
                          SUM((orders.operation = 'bonus')::integer) AS bonus_count, 
                          SUM((orders.operation = 'gift')::integer) AS gift_count ").
                 group("admins.id ")

# access each columns as
admin.name, admin.bonus_count, admin.gift_count

其他选项是使用预先加载,它将使用两个查询但可能更快

@admins  = Admin.includes(:orders)

# in admin.rb
def orders_count(type)
  # Don't use where here as it would make a separate query instead of using eager loading records
   orders.select{|x| x.operation == type}.count
end 

# access each columns as
admin.name, admin.orders_count("bonus"), admin.orders_count("gift")