下面的等效查找语句是什么?
@mostviews = Post.find_by_sql("select posts.id,posts.title from posts inner join countpages on countpages.post_id = posts.id order by countpages.counts desc limit 5")
@temp = Post.find_by_sql("SELECT posts.id,posts.title, comment_count.count FROM posts INNER JOIN (SELECT post_id, COUNT(*) AS count FROM comments GROUP BY post_id) AS comment_count ON comment_count.post_id = posts.id ORDER BY count DESC LIMIT 5;")
是否可以使用find或where函数获得相同的结果?
答案 0 :(得分:4)
Post.select("posts.id, posts.title").joins(:countpage).order("countpages.counts desc").limit(5)
这假设countpage是一个关联。否则,您可以在联接中更明确(“INNER JOIN ...”)