2013-07-08 4 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에서 쿼리를 실행하여 정상적으로 작동했지만 쿼리의 결과를 얻는 방법을 잘 모르겠습니다. (숫자 => 개수 (*)가 될 것으로 예상합니다) – Bala

+0

조금 더 많은 정보로 답변을 업데이트했습니다. 하나의 가능한 유스 케이스. –

관련 문제