使用嵌套表

时间:2016-02-10 16:44:56

标签: ruby-on-rails postgresql activerecord

我正在尝试使用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

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

例如,我们有活动记录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")