【问题标题】:How do you get a count of a subquery in Active Record?如何获得 Active Record 中子查询的计数?
【发布时间】:2016-02-19 23:38:00
【问题描述】:

我正在将 SQL 查询迁移到 Active Record。这是一个简化的版本:

SELECT count(*) FROM (
  SELECT type, date(created_at)
  FROM notification_messages
  GROUP BY type, date(created_at)
) x

我不确定如何在 Active Record 中实现这一点。这可行,但很混乱:

sql = NotificationMessage.
  select("type, date(created_at) AS period").
  group("type", "period").
  to_sql
NotificationMessage.connection.exec_query("SELECT count(*) FROM (#{sql}) x")

另一种可能性是在 Ruby 中进行计数,但效率会降低:

NotificationMessage.
  select("type, date(created_at) AS period").
  group("type", "period").
  length

有没有更好的解决方案?

【问题讨论】:

    标签: ruby-on-rails postgresql subquery rails-activerecord


    【解决方案1】:

    Rails 具有from 方法。所以我会写它:

    NotificationMessage
      .from(
        NotificationMessage
          .select("type, date(created_at)")
          .group("type, date(created_at)"), :x
      ).count
    

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多