如何使用Arel编写此查询

时间:2013-07-08 14:59:11

标签: ruby arel

我刚开始使用Arel(使用MySQL),我对基本查询感到满意。但是我陷入了多联接。我有以下查询,我想使用Arel?可以提供一些帮助。

 SELECT count(*)
  FROM    table_1 p
       LEFT JOIN
          (SELECT pid
             FROM table_2 s LEFT JOIN table_3 i ON s.key = i.key
            WHERE i.default = 'y') AS table_4
       ON p.pid = table_4.pid AND isnull(table_4.pid) AND p.show = 'y'

这是我到目前为止所管理的(显然最终查询无效)

=>子查询

table_2.select(:pid).joins(table_3).
   where(:table_3 => {:default => 'y'}).as('table_4')

=>最终

table_1.joins(:table_1 => :table_4).
   where (:table_4 => {ISNULL(:pid)}, :table_1 => {:show = 'y'})

1 个答案:

答案 0 :(得分:2)

你可以这样做。我删除了没有必要的别名,但你可以根据需要添加它:

table_1 = Arel::Table.new(:table_1)
table_2 = Arel::Table.new(:table_2)
table_3 = Arel::Table.new(:table_3)

table_4 = table_2
  .join(table_3, Arel::Nodes::OuterJoin) # specifies join using LEFT OUTER
  .on(table_2[:key].eq(table_3[:key])) # defines join keys
  .where(table_3[:default].eq('y')) # defines your equals condition
  .project(table_2[:pid]).as('table_4') # AREL uses project not select

query = table_1
  .join(table_4, Arel::Nodes::OuterJoin)
  .on(table_1[:pid].eq(table_4[:pid]))
  .where(table_4[:pid].eq(nil).and(table_1[:show].eq('y'))) # multiple conditions
  .project("count(*)")

# The AREL documentation is pretty good: 
#   https://github.com/rails/arel/blob/master/README.markdown

# If you are using ActiveRecord you can do:
ActiveRecord::Base.connection.execute(query.to_sql)