sql - 对多个父记录的子项属性进行 SUM 运算

标签 sql ruby-on-rails ruby activerecord

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

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

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

最佳答案

你可以试试:

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

关于sql - 对多个父记录的子项属性进行 SUM 运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032322/

相关文章:

Ruby:合并嵌套哈希

ruby-on-rails - 在 Rails 上使用 Streamio FFMPEG 的正确视频路径是什么

mysql - 寻找一种优雅的方式将精选的对象从一个数据库复制到另一个数据库

mysql - 显示mysql中不同表的结果

mysql - SQL 检查某个值是否存在于任何列中并返回另一列列出的值

ruby-on-rails - 在 JSON 响应中包含图像的 ActiveStorage URL?

html - 如何在内联 CSS 中插入引号?

Ruby Guard 问题 - 'Please install the sqlite3 adapter' - railstutorial.org

java - Hibernate 获取行在结果集中的位置

php - mySQL 按特定值排序,然后按 DESC 排序?