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