开发者

Need ruby on rails equivalent query for this sql query -->

SELECT 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;

or

SELECT posts.title, comment_count.count FROM posts 
       JOIN (SELECT post_id, COUNT(*) AS count FROM comments GROUP BY post_id)
       AS comment_count ON c开发者_运维问答omment_count.post_id = posts.id  
       ORDER BY count DESC LIMIT 5;


In this case you're probably better off by-passing ActiveRecord and just invoking that query via your native driver and getting back just an array or a Hash.

sql = <<-SQL
SELECT 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;
SQL
posts = Post.connection.select_rows(sql)

posts is now an array of Hashes

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜