Arel连接子查询

时间:2018-08-16 00:18:49

标签: sql ruby-on-rails join arel

我是Rails和Arel的新手 我创建了一个联接查询,但是写得不好

join_query = 
ActiveRecord::Base.connection.execute <<~SQL.strip_heredoc
        (
          SELECT schools.name, sum(q.enrollment), count(*) FROM schools LEFT JOIN
            (
              SELECT sites.school_id, sites.enrollment  FROM sites JOIN projects ON
              sites.project_id = projects.id
              WHERE sites.school_id IS NOT NULL and projects.type IN ('Startup') AND projects.deleted_at IS NULL
            ) q
          ON q.school_id = schools.id
          GROUP BY schools.name
        )
      SQL
join_query.values

如何使用Arel编写?
另外,您能指出我关于该主题的优秀教程吗?
预先感谢

1 个答案:

答案 0 :(得分:0)

这就是我想出的给定SQL:

schools = Arel::Table.new("schools")
sites = Arel::Table.new("sites")
projects = Arel::Table.new("projects")

join = sites.project(:school_id, :enrollment)
  .join(projects).on(sites[:project_id].eq(projects[:id]))   
  .where(
    sites[:school_id].not_eq(nil)
    .and(projects[:type].in("Startup"))
    .and(projects[:deleted_at].eq(nil))
  )

q = Arel::Table.new(join).alias(:q)

schools.project(:name, q[:enrollment].sum, Arel.star.count)
  .join(join, Arel::Nodes::OuterJoin).on(q[:school_id].eq(schools[:id]))
  .group(schools[:name])

作为新手,这些是我经常访问的参考资料:

https://www.rubydoc.info/github/rails/arel(官方文档)

https://devhints.io/arel(非常有用的备忘单,但不完整)

https://gist.github.com/mildmojo/3724189(左外部联接的示例)

https://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html(有关Arel的全面指南)