我有以下树表
表士兵
ID | NAME --------------- 22 | Franck 23 | Paul 24 | Bill
表soldier_status_history
soldier_id | date_record | soldier_status ----------------------------------------------------------------- 22 | 2012-12-07 18:09:58 | 37 22 | 2012-12-08 18:10:11 | 38 22 | 2012-12-10 18:20:25 | 41 23 | 2011-08-17 23:59:10 | 37 23 | 2011-08-19 23:59:11 | 38 23 | 2011-08-22 00:00:00 | 41 23 | 2011-08-25 12:00:22 | 38 24 | 2011-08-24 19:18:43 | 37 24 | 2011-08-29 19:18:44 | 38
表soldier_values
id | key ---------------- 37 | onduty 38 | available 40 | vacation 41 | ill
是否有可能成为一个将加入他们的选择,并且只返回来自表士兵_status_history的记录,对于特定士兵的最后日期_记录,soldier_status不是“假期”或“生病”
我的意思是这个名叫“保罗”的人我们有树记录,但最后一个记录他生病了,因为这个人不应该被显示,直到它的状态没有改变。
23 | 2011-08-17 23:59:10 | 37 23 | 2011-08-19 23:59:11 | 38 23 | 2011-08-22 00:00:00 | 41
答案 0 :(得分:0)
select * from
soldier s
left join
(select
soldier_id,
max(date_record) maxDate_record
from soldier_status_history
group by soldier_id
) s2
on (s.id=s2.soldier_id)
left join soldier_status_history s3
on (s2.soldier_id=s3.soldier_id) and (s2.maxDate_record=s3.date_record)
where s3.soldier_status not in (40,41)
答案 1 :(得分:0)
试试这个:
SELECT
h.*
FROM Soldier s
INNER JOIN soldier_status_history h ON s.ID = h.soldier_id
INNER JOIN
(
SELECT Soldier_id, MAX(date_record) latestDate
FROM soldier_status_history
GROUP BY soldier_id
) l ON h.soldier_id = s.ID
AND DATE(l.latestDate) = DATE(h.date_record);
这会给你:
| SOLDIER_ID | DATE_RECORD | SOLDIER_STATUS |
-----------------------------------------------------------------
| 22 | December, 10 2012 18:20:25+0000 | 41 |
| 23 | August, 25 2011 12:00:22+0000 | 38 |
| 24 | August, 29 2011 19:18:44+0000 | 38 |