2011-11-04 2 views
2

내 where 절에 약간 문제가 있습니다.레일즈 3 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 

내 오류가있다 : -/

누군가가 있습니까 내 문제에 대한 해결책?

마이클

답변

3

당신이 점점 오류가처럼

조항이 있어야한다.

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) 

임 같은 가진 질의를하지 만들 수 있습니다 확실히 귀하의 쿼리에 대한 구문을 가지고 있지만 당신은 그 조항과 그룹 조항을 사용하여 그것을 고칠 수 있어야합니다.

+1

숀, 덕분에 많은 도움;) – sufu90

0

.where('sum(pallet_purchase_position_assignments.quantity) < purchase_positions.quantity') 경우 당신은에서 SUM() 함수를 사용할 수 없습니다 - 그 오류를 던지고있다. GROUP BY 절을 사용하지 않기 때문에 where purchase_positions.quantity > (select sum(purchase_positions.quantity))

관련 문제