我有以下表格
Actions: actionID, time, type
States: stateID, time, type
我需要找出行动执行时的当前状态。
所以我开始使用像
这样的东西SELECT actions.actionID, states.stateID
FROM actions, states
WHERE states.time < actions.time
这给了我一个结果表,其中包含在给定操作发生之前存在的所有状态。但是我在行动之前只需要最后状态。
所以我需要某种基于max(states.stateID)的GROUP BY,但老实说我无法弄清楚如何解决这个问题!
修改
所以如果actions表包含这个:
actionID time type
1 '2012-10-30 02:05:00' 100
2 '2012-10-30 02:11:00' 200
状态表包含:
stateID time type
11 '2012-10-30 02:00:00' A
12 '2012-10-30 02:10:00' B
13 '2012-10-30 02:15:00' A
我想要以下结果:
actionID stateID
1 11 // Because before action 1, the state that prevailed was 11
2 12 // Because before action 2, the state that prevailed was 12
答案 0 :(得分:2)
试试这个:
select t.actionID,t.stateID,a.type action_type,s.type state_type from
(SELECT actions.actionID,max(states.stateID) stateID
FROM actions, states
WHERE states.time < actions.time
group by actions.actionID)as t
join
actions a on t.actionID=a.actionID
join
states s on t.stateID=s.stateID