需要ruby on rails等效查询此sql查询 - >

时间:2011-07-17 12:48:04

标签: ruby-on-rails

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;

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 comment_count.post_id = posts.id  
       ORDER BY count DESC LIMIT 5;

1 个答案:

答案 0 :(得分:1)

在这种情况下,你最好绕过ActiveRecord,只需通过你的本机驱动程序调用该查询,然后只返回一个数组或哈希。

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现在是一个哈希数组