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
有沒有更好的解決辦法?