如何获得 Active Record 中子查询的计数? [英] How do you get a count of a subquery in Active Record?
本文介绍了如何获得 Active Record 中子查询的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将 SQL 查询迁移到 Active Record.这是一个简化的版本:
I'm migrating an SQL query to Active Record. Here is a simplified version:
SELECT count(*) FROM (
SELECT type, date(created_at)
FROM notification_messages
GROUP BY type, date(created_at)
) x
我不确定如何在 Active Record 中实现这一点.这可行,但很混乱:
I'm not sure how to implement this in Active Record. This works, but it's messy:
sql = NotificationMessage.
select("type, date(created_at) AS period").
group("type", "period").
to_sql
NotificationMessage.connection.exec_query("SELECT count(*) FROM (#{sql}) x")
另一种可能性是在 Ruby 中进行计数,但效率会降低:
Another possibility is to do the count in Ruby, but that would be less efficient:
NotificationMessage.
select("type, date(created_at) AS period").
group("type", "period").
length
有没有更好的解决方案?
Is there a better solution?
推荐答案
Rails 有 from
方法.所以我会写它:
Rails has the from
method. So I would write it:
NotificationMessage
.from(
NotificationMessage
.select("type, date(created_at)")
.group("type, date(created_at)"), :x
).count
这篇关于如何获得 Active Record 中子查询的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文