【发布时间】:2011-10-24 09:22:40
【问题描述】:
我的上一篇文章是关于使用 LEFT OUTER JOIN 条件编写 SQL 查询的最佳方法:
LEFT OUTER JOIN with conditions (where, order by)?
现在,我需要将那段优秀的 SQL 转换为甜蜜的 Active Record 查询(Rails 3)。 ;-)
我有 2 个模型:
培训 has_many :training_histories
TrainingHistory belongs_to :training
如何编写范围以获取下面的 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
我想检索 TRAININGS 的所有记录并添加 TRAINING_HISTORIES 的最后一个有效(又名已完成)关联记录。
有什么建议吗?
谢谢
【问题讨论】:
-
为什么不做 2 个选择请求?
标签: mysql sql ruby-on-rails-3 postgresql scope