【发布时间】: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