Rails 3在where子句中使用sum()

时间:2011-11-04 11:07:03

标签: mysql ruby-on-rails-3 activerecord

我的where子句有点问题。

PurchasePosition.where(:purchase_order_id => 996).where('sum(pallet_purchase_position_assignments.quantity) < purchase_positions.quantity').includes(:pallet_purchase_position_assignments)

我的模特:

class PurchasePosition < ActiveRecord::Base
  has_many :pallet_purchase_position_assignments, :class_name => "PalletPurchasePositionAssignment"
  has_many :pallets, :class_name => "Pallet", :through => :pallet_purchase_position_assignments
end

class Pallet < ActiveRecord::Base
  has_many :pallet_purchase_position_assignments, :class_name => "PalletPurchasePositionAssignment"
  has_many :purchase_positions, :class_name => "PurchasePosition", :through => :pallet_purchase_position_assignments
end

class PalletPurchasePositionAssignment < ActiveRecord::Base
  belongs_to :pallet, :class_name => "Pallet", :foreign_key => "pallet_id"
  belongs_to :purchase_position, :class_name => "PurchasePosition", :foreign_key => "purchase_position_id"
end

我得到的只是一个Mysql错误

ActiveRecord::StatementInvalid: Mysql2::Error: Invalid use of group function

我绝对不知道我的错误在哪里: - /

有人为我的问题找到解决方案吗?

迈克尔

2 个答案:

答案 0 :(得分:3)

您得到的错误是因为您没有使用group by子句。

在mysql和大多数数据库中,如果要在select中使用求和(或按列的任何组)而不是使用HAVING子句而不是WHERE子句

PurchasePosition.where(:purchase_order_id => 996).having('sum(pallet_purchase_position_assignments.quantity) < purchase_positions.quantity').includes(:pallet_purchase_position_assignments).sum("pallet_purchase_position_assignments.quantity

例如,如果我有一个像这样的表:

 create_table "leaders", :force => true do |t|
   t.integer  "leaderable_id"
   t.string   "leaderable_type"
   t.integer  "county_id"
   t.integer  "us_state_id"
   t.integer  "recruits"
   t.integer  "hours"
   t.datetime "created_at"
   t.datetime "updated_at"
   t.datetime "last_run_dt"
 end

然后我可以创建一个像这样的查询

Leader.having("sum(hours) > 150").group(:leaderable_type).sum(:hours)

我不确定我的查询语法是否合适,但你应该能够使用having子句和group子句来修复它。

答案 1 :(得分:0)

你不能在where子句.where('sum(pallet_purchase_position_assignments.quantity) < purchase_positions.quantity')中使用SUM()函数 - 这就是抛出错误。

该条款应该是这样的 where purchase_positions.quantity > (select sum(purchase_positions.quantity))