2011-11-23 4 views
0

postgresql을 사용하고 있습니다.한 번 이상 같은 테이블에 가입하는 방법

custom_field_answers라는 테이블이 있습니다. 데이터는 다음과 같습니다.

Id | product_id | value  | number_value | 
4 | 2   |   | 117   | 
3 | 1   |   | 107   | 
2 | 1   | bangle  |    | 
1 | 2   | necklace |    | 

는 내가 코드를 다음과 같이 그 SQL을 생산하기 위해 노력 미만 50

SELECT p.* 
FROM "products" AS p 
INNER JOIN "custom_field_answers" AS a1 ON p."id" = a1."product_id" 
INNER JOIN "custom_field_answers" AS a2 ON p."id" = a1."product_id" 
WHERE a1."value" = 'bangle' AND a2."number_value" < 50 

'팔찌'와 NUMBER_VALUE으로 TEXT_VALUE 한 모든 제품을 찾고 싶어요.

conditions = <conditions from arel> 
relation = self.scoped 
conditions.each do |condition| 
    relation = relation.merge(where(condition)) 
end 
joins(:custom_field_answers).merge(relation) 
relation.to_a 

이 SQL은 (맨 위에 언급 한) 원하는 SQL과 유사하지 않습니다 볼 수 있듯이이 SQL

SELECT "products".* FROM "products" INNER JOIN "custom_field_answers" 
ON "custom_field_answers"."product_id" = "products"."id" 
WHERE ("custom_field_answers"."value" ILIKE 'bangle') 
AND ("custom_field_answers"."number_value" < 50) 

다음 생성합니다.

는 나는 아직도이

relation = self.scoped 
conditions.each do |condition| 
    relation = relation.merge(where(condition).joins(:custom_field_answers)) 
end 
relation.to_a 

행운처럼 조금을 코드 조인 이동했습니다.

누구나 각 관계에 대해 새로운 조인을 강제하는 방법을 알고 있습니다. 레일 3.1.1을 사용하고 있습니다.

답변

-1
Select * from products where product_id 
IN 
(Select product_id from custom_answers 
    where 
    text_value = 'bangle' 
    AND number_value<50) 
6

이들과 같은 '비표준'쿼리에 대한 가장 좋은 방법은 바로 Arel에 가서하는 것입니다. 이 같은

뭔가 작업을해야합니다 :

# in your model 
p = Arel::Table.new(:products, :as => 'p') 
a1 = Arel::Table.new(:custom_field_answers, :as => 'a1') 
a2 = Arel::Table.new(:custom_field_answers, :as => 'a2') 

relation = p. 
    project(Arel.sql('*')). 
    join(a1).on(p[:id].eq(a1[:product_id])). 
    join(a2).on(p[:id].eq(a2[:product_id])) 

relation = relation.where(a1[:value].eq('bangle')).where(a2[:number_value].lt(50)) 

relation.to_sql #should return the SQL you're after 

과 레일 Arel 래퍼로 좋은,하지만 당신은 당신의 코드에서 원시 SQL에 싶지 드롭을 할 경우 복잡한 쿼리 것이 유일한 방법하지 않습니다.

이 정보가 도움이됩니까?

관련 문제