【问题标题】:Rails, SQL - perform a Count and Select in a single queryRails,SQL - 在单个查询中执行计数和选择
【发布时间】:2016-10-25 07:31:17
【问题描述】:

有没有办法做一个查询来做一个选择和一个计数,并取回一个包含这两个值的数组?例如:

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'])

【问题讨论】:

  • 不,使用 Active Record DSL 你不能
  • 啊,好吧。你介意帮我添加我添加的内容吗?我将帖子作为数组返回,但 total_count 最终出现在每个数组中,并且始终为一个。

标签: sql ruby-on-rails postgresql activerecord


【解决方案1】:

我想这就是你想要的:

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

单个查询返回一个以 total_count 作为属性的 Post 对象数组。

【讨论】:

  • 我在尝试这个时只返回了 1 个。我也在尝试做一个完整的选择,所以它会像Post.where('category = ?', 'somecategory').select('*, count(*) as total_count').group(:id).limit(10)。附带说明一下,这是一个不错的小技巧,可以添加不需要在数据库中的列 - 无需执行类似 as_json.merge! 的操作
【解决方案2】:

我发现这行得通:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2016-08-24
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多