开发者

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

开发者 https://www.devze.com 2023-03-21 01:10 出处:网络
SELECT posts.title, comment_count.count FROM posts INNER JOIN (SELECT post_id, COUNT(*) AS count FROM comments GROUP BY post_id)
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

精彩评论

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

关注公众号