Rails,SQL - 在单个查询中执行计数和选择

时间:2016-10-25 07:31:18

标签: sql ruby-on-rails postgresql activerecord

有没有办法执行单个查询来同时执行select和count,并获取具有这两个值的数组?例如:

posts = Post.where(category = ?, 'somecategory').limit(10)
count = Post.where(category = ?, 'somecategory').count

编辑:

data = Post.find_by_sql(["SELECT count(category) AS total_count, * FROM posts WHERE category = ? GROUP BY posts.id LIMIT 10",'somecategory'])

2 个答案:

答案 0 :(得分:0)

我发现这个有用:

data = Post.find_by_sql(["SELECT count(*) OVER (), p.* FROM posts p WHERE category = ? GROUP BY p.id LIMIT 10",'somecategory'])
然而,这个问题是,它将计数放在每个帖子中。因此,要获得计数,您必须这样做: count = data.first.count。如果有人发现这一点,我认为这可能是您的下一个目的地:Rails, how to sanitize SQL in find_by_sql

答案 1 :(得分:0)

我认为这就是你想要的:

Post.where('category = ?', 'somecategory').select('id, count(id) as total_count').group(:id).limit(10)

单个查询返回一个Post对象数组,其中 total_count 作为其属性。