I have the following tables
Actions: actionID, time, type
States: stateID, time, type
I need to find out what was the current state at the time the actions were performed.
So I started up with something like
SELECT actions.actionID, states.stateID
FROM actions, states
WHERE states.time < actions.time
This gives me a result table with ALL the states that existed before a given action took place. But I need only the LAST state before the action.
So I need some kind of GROUP BY based on max(states.stateID) but I honestly can’t figure out how to solve this one !
EDIT
So if actions table contains this:
actionID time type
1 '2012-10-30 02:05:00' 100
2 '2012-10-30 02:11:00' 200
And states table contains this:
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
I would like the following result:
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
try this:
SQL FIDDLE DEMO