2013-07-08 171 views
1

我剛開始使用Arel(含MySQL),我對基本查詢感到滿意。不過,我被困在多連接。我有我想要使用Arel的下面的查詢?可以做一些幫助。如何使用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'}) 

回答

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) 
+0

哇,很棒。加工!。如果你能夠通過你的答案,將不勝感激。 – Bala

+0

我在irb中運行了查詢,工作正常,但我不太清楚如何獲得查詢結果(我希望這是一個數字=> count(*)) – Bala

+0

我用更多的信息更新了我的答案和一個可能的用例。 –