【发布时间】:2017-05-19 09:48:46
【问题描述】:
我有一个查询以我想要的方式工作,直接执行 SQL,但我很好奇(只是为了我自己的学习目的)是否可以在 ActiveRecord 语句中完成同样的事情?
我最苦恼的部分是这个查询的 COALESCE 部分,它只是确保 LEFT JOIN 中的任何 NULL 值都被计为零,以保持总和的顺序。
有什么想法吗?我正在使用 Postgres。
SELECT Inventories.id, Inventories.name, Inventories.unit_of_measure,
COALESCE(Sum(Stocks.count),0) as totalcount
FROM Inventories
LEFT JOIN Stocks
ON Inventories.id = Stocks.inventory_id
WHERE Inventories.property = 'material' AND Inventories.organization_id = #{current_organization.id}
GROUP BY Inventories.id, Stocks.inventory_id
ORDER BY totalcount ASC
LIMIT(5)")
这是我得到的最接近的 AR 等价物。当我尝试添加一个总和或类似的东西时,就会出错。
@lowmaterials = current_organization.inventories.materials.left_joins(:stocks).group(:id, :inventory_id).order(count: :asc).limit(5)
【问题讨论】:
标签: sql ruby-on-rails postgresql activerecord