2011-11-04 21 views
2

我有一個小問題,我的where子句。Rails 3使用總和()在哪裏條款

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 

我是絕對不知道在哪裏我的錯誤在於: -/

難道有人有解決我的問題?

邁克爾

回答

3

你得到的錯誤是因爲你不使用GROUP BY子句。

在MySQL和大多數數據庫中,如果你想使用求和(或列中的任何組)中選擇比你使用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

謝謝肖恩,這幫了很多;) – sufu90

0

where子句.where('sum(pallet_purchase_position_assignments.quantity) < purchase_positions.quantity')你不能在使用SUM()函數 - 這是引發錯誤。

的條款應這麼 where purchase_positions.quantity > (select sum(purchase_positions.quantity))