1

我刚刚开始使用 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'})
4

1 回答 1

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)
于 2013-07-08T17:04:03.403 回答