gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:05:02 25 4
gpt4 key购买 nike

我的 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

我完全不知道我的错误在哪里:-/

有人能解决我的问题吗?

迈克尔

最佳答案

您收到的错误是因为您没有使用 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

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

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

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

关于mysql - Rails 3 在 where 子句中使用 sum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8008312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com