2011-08-10 5 views
1

내 마지막 게시물은 LEFT OUTER에 조건이있는 SQL 쿼리를 작성하는 최선의 방법에 있던은 가입 :
LEFT OUTER JOIN with conditions (where, order by)?SQL 쿼리를 레일스 활성 레코드 쿼리로 변환하는 방법?

을 지금, 나는 달콤한 액티브 레코드 쿼리 (레일 3에 SQL의 좋은 조각을 변환해야).

교육 has_many : 결과가 SQL 아래 검색 얻을 내가 범위를 쓸 수있는 방법을 교육

: training_histories

TrainingHistory belongs_to ;-)

나는이 개 모델이 ?

SELECT tc.id, tc.name, tc.order, 
th.id as history_id, th.finished_at, th.score 
FROM trainings tc 
LEFT OUTER JOIN training_histories th ON th.training_id = tc.id 
    and th.id = 
    (SELECT th1.id from training_histories th1 where th1.training_id = tc.id 
    and th1.finished_at is not null 
    order by th1.finished_at desc limit 1) 
WHERE tc.id > 4 
AND tc.id < 8 
GROUP BY tc.id 
ORDER BY tc.order_by ASC, tc.id ASC 

나는 교육의 모든 레코드를 검색하고 TRAINING_HISTORIES의 마지막 유효 (일명 완료) 관련 레코드를 추가 할 수 있습니다.

제안 사항?

는 레일 3

+0

2 가지 선택 요청을하지 않는 이유는 무엇입니까? –

+0

그리고 루비에서 데이터를 병합 하시겠습니까? ;-) –

답변

7

,이 시도 감사 :

Training.select("trainings.id, trainings.name, trainings.order, 
       trainings.id AS history_id, training_histories.finished_at, 
       training_histories.score"). 
     joins("LEFT OUTER JOIN training_histories 
       ON training_histories.training_id = trainings.id 
       AND training_histories.id = (SELECT th1.id FROM training_histories th1   
              WHERE th1.training_id = tc.id 
              AND th1.finished_at IS NOT NULL 
              ORDER BY th1.finished_at DESC LIMIT 1)"). 
     where("trainings.id > 4 AND trainings.id < 8"). 
     group("trainings.id"). 
     order("trainings.order_by ASC, trainings.id ASC") 

기본적으로, 당신은 단지 레일 3 파인더 방법으로 미리 작성된 쿼리를 변환하고 있습니다.

관련 문제