【问题标题】:SUM operation on attributes of children of multiple parent records对多条父记录的子项属性进行求和运算
【发布时间】:2015-12-01 23:36:45
【问题描述】:

我的产品模型中有这个方法可以满足我的需要:

def self.available
  available = []
  Product.all.each do |product|
    if product.quantity > product.sales.sum(:quantity)
      available << product
    end
  end
  return available
end

但是,我想知道是否有更有效的方法来做到这一点,也许只需要一次调用数据库。

【问题讨论】:

    标签: sql ruby-on-rails ruby activerecord


    【解决方案1】:

    你可以试试:

    Product.where("products.quantity > Coalesce((select sum(s.quantity) from sales s where s.product_id = products.id), 0)")
    

    【讨论】:

      【解决方案2】:

      由于sum 查询,这将创建与您拥有的产品数量相等的查询数量。这是我认为可以减少数据库查询的一种方法。

      map = Sale.joins(:product)
        .group("products.id", "products.quantity").sum(:quantity).to_a
      

      这将产生一个类似于

      的数组
      [[[1,20],30], [[2,45], 20]]
      

      这对应于[[[product_id, product_quantity], sold_quantity ]]

      现在循环这个数组并比较值。

      available = []
      map.each do |item|
        if item[0][1] > item[1]
          available << item[0][0]
        end
      end
      

      现在您已经填充了 available 数组,请执行另一个查询。

      available = Product.where(id: available)
      

      现在您在两个查询中得到了相同的输出,而不是 Product.count (N) 查询数。此解决方案有时可能效率低下,但如果我有任何想法,我会定期更新它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多