2011-08-10 9 views
1

私の最後のポストは、JOINをLEFT OUTER上の条件付きのSQLクエリを記述するための最良の方法だった:
LEFT OUTER JOIN with conditions (where, order by)?SQLクエリをRailsのアクティブレコードクエリに変換する方法?

を、私は甘いアクティブレコードクエリ(Railsの3にSQLの良い作品を変換する必要があります)。 ;-)

私は2つのモデルがあります:

トレーニングにhas_many:training_histories

TrainingHistory belongs_toの:私は、以下のSQLを取得する結果を得るためにスコープを書くことができますどのように

を訓練します?

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") 

は基本的に、あなただけのRails 3の検索メソッドにあなたの前の書かれたクエリを変換しています。

関連する問題