2016-02-19 60 views
1

我正在将SQL查询迁移到Active Record。这里是一个简化版本:如何获得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 

有没有更好的解决办法?

回答

4

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

NotificationMessage 
    .from(
    NotificationMessage 
     .select("type, date(created_at)") 
     .group("type, date(created_at)"), :x 
).count 
相关问题