[英]How do I execute a subselect (or large group by) of SQL in Rails 4 with ActiveModel?
我想執行這種類型的SQL並獲取Model1的數組:
select model1.*,
(select sum(prop) from model2 where model2.model1_id = model1.id) as total
from model1
where model1.parent_id is null
order by total desc
我嘗試使用
@ parent.model1.select(“ model2.prop”)。where(parent_id:nil).group(:id).order(:prop =>:desc)
但是它給出了一個有關“缺少表的FROM子句條目”的錯誤。 我不知道如何在Rails中使用子選擇,並且它不在指南中 。 我唯一想做的就是遍歷每個model1並找到我要尋找的屬性的總和,但這將生成N + 1個查詢,並且與1個直接SQL相比確實很慢。 我想對model1的每個單個屬性使用group by和grouping也可以,但是聽起來很混亂。
我做到了!
@ post.comments.select(Comment.columns.map {| c | c.name})。select(“(從選票中選擇合並(sum(vote),0)作為投票,而votes.comment_id = comments.id)為total“)。order(” total desc“)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.