我正在使用 MySql(本地)和 Postgresql(Heroku)数据库开发 Rails3 项目。
我需要在 LEFT OUTER JOIN 上设置条件,但我不知道如何操作。
我有 2 个表 TRAININGS 和 TRAINING_HISTORIES。
我想检索 TRAININGS 的所有记录并添加 TRAINING_HISTORIES 的最后一个有效(又名已完成)关联记录。
表格培训
id name order_by
5 A 1
6 B 2
7 C 3
表 TRAINING_HISTORIES
id training_id finished_at score
43 5 2011-06-06 10
44 5 null null
45 6 2011-07-07 11
46 6 2011-08-08 14
47 6 null null
48 6 2011-09-09 18
49 6 null null
50 7 null null
51 7 2011-10-10 19
这是我的 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
WHERE tc.id > 4
AND tc.id < 8
GROUP BY tc.id
ORDER BY tc.order_by ASC, tc.id ASC
我得到的结果:
id name order history_id finished_at score
5 A 1 43 2011-06-06 10
6 B 2 45 2011-07-07 11
7 C 3 50 null null
- 查询检索每个连接的第一个 training_history
我需要的结果:
id name order history_id finished_at score
5 A 1 43 2011-06-06 10
6 B 2 48 2011-09-09 18
7 C 3 51 2011-10-10 19
- 在这种情况下:检索到的是最后完成的 training_history...
非常感谢任何建议!
谢谢
编辑:如果有人能回答 Rails 部分,那也很棒 ;-)
How to Convert SQL Query to Rails Active Record Query?
最佳答案
试试这个查询,它会为您提供每一次训练以及每一次的最近训练历史:
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
关于mysql - 有条件的左外连接(在哪里,排序依据)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7015839/