Ruby Gem Squeel,如何编写自联接

时间:2013-04-29 20:30:42

标签: sql ruby activerecord squeel

我正在尝试使用ruby gem Squeel

编写以下查询
SELECT COUNT(*)
FROM(
  SELECT
    a.end_at AS START,
    Min(b.start_at) AS END
  FROM periods AS a
  JOIN periods AS b ON b.season_id IN (1,2,3) AND a.end_at <= b.start_at
  WHERE a.season_id IN (1,2,3)
  GROUP BY a.end_at
  HAVING a.end_at < MIN(b.start_at)
) AS gaps
WHERE
  gaps.START < '2013-05-17' AND gaps.END > '2013-05-05';

关于如何实现这一目标的任何想法?

我可以使用:

获取seasons_ids
seasons = self.seasons
Period.where{season_id.in(seasons.select{id})}

但是自我加入条件,到目前为止我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

这类似于我尝试过的here

我会尝试使用子查询,将Period连接到自身,如下所示:

class Period < ActiveRecord::Base
  attr_accessible :end_at, :season_id, :start_at

  belongs_to :season

  scope :in_seasons, ->(season_ids) { joins{season}.where{id.in(season_ids)} }

  def self.find_gaps(start_date, end_date)
    season_ids = ["1", "2", "3"]
    scope = select{[end_at.as(`gap_start`), `min(self_join.start_at)`.as(`gap_end`)]}
    scope = scope.joins{"LEFT JOIN (" + Period.in_seasons(season_ids).to_sql + ") AS self_join ON self_join.end_at <= periods.start_at"}
    scope = scope.where{(`self_join.start_at` != nil) & (`gap_start` < start_date) & (`gap_end` > end_date)}
    scope = scope.group{`gap_end`}.having{end_at < `min(self_join.start_at)`}
  end
end

在rails控制台中,Period.find_gaps('2001-01-01', '2010-01-01').to_sql生成(格式化是我自己的):

SELECT 
  \"periods\".\"end_at\" AS gap_start, 
  min(self_join.start_at) AS gap_end 
FROM \"periods\" 
  LEFT JOIN 
    (SELECT \"periods\".* 
     FROM \"periods\" 
       INNER JOIN \"seasons\" ON \"seasons\".\"id\" = \"periods\".\"season_id\" 
     WHERE \"periods\".\"id\" IN (1, 2, 3)
    ) AS self_join ON self_join.end_at <= periods.start_at 
WHERE ((self_join.start_at IS NOT NULL AND gap_start < '2001-01-01' AND gap_end > '2010-01-01')) 
GROUP BY gap_end 
HAVING \"periods\".\"end_at\" < min(self_join.start_at)

看起来你想要的是......至少在内部。

希望它有所帮助。