我正在尝试使用ActiveRecord进行下一个查询,不知道如何在不使用find_by_sql调用的情况下实现这个SQL结果。

SELECT *
FROM table_x AS a,
    (SELECT locator, max(day_parsed) AS max_day
     FROM table_x
     WHERE day_parsed BETWEEN params[:day_from] AND params[:day_to]
     GROUP BY locator) AS b
WHERE a.locator = b.locator
AND a.day_parsed = b.max_day

知道吗?

最佳答案

例如,我们有活动记录TableX,它的表名是table_x,因此查询将是:

from = params[:day_from]
to   = params[:day_to]

TableX.joins("JOIN (
                     SELECT locator, max(day_parsed) AS max_day
                     FROM table_x
                     WHERE day_parsed BETWEEN #{from} AND #{to}
                     GROUP BY locator
                   ) as b ON b.locator = table_x.locator")
      .where("table_x.day_parsed = b.max_day")

关于ruby-on-rails - 带有嵌套表的ActiveRecord查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35321042/

10-13 00:00