I’m trying to write a query where I’d like to get a list of users’s last “special actions”, so I have these tables:
table_users
id username email etc.
1 moloc a@mail.com etc.
2 lilly b@mail.com etc.
3 sammm c@mail.com etc.
table_special_actions
id user_id action_id date
1 3 25 2010-11-01 22:51:56
2 3 37 2010-11-02 18:09:33
3 3 265 2010-11-03 07:20:12
table_actions
id action
1 Open a secret
2 Level up
3 Open magic door
etc. etc.
My objective is to get an user list where I have only the last special action for each one, so I’ve thought something like this:
SELECT *
FROM table_users AS users
LEFT JOIN (
SELECT user_id, action_id, MAX(date) AS action_date
FROM table_special_actions
GROUP BY user_id
ORDER BY action_date
) s_actions
ON s_actions.user_id = users.user_id
LEFT JOIN table_actions AS actions
ON s_actions.action_id = actions.id
This doesn’t work properly because it’s return this:
-----users----- ------------s_actions------------ -----actions-----
id username action_id date action
3 sammm 25 2010-11-03 07:20:12 Action linked to action_id 25
I’ve expected to get this:
-----users----- ------------s_actions------------ -----actions-----
id username action_id date action
3 sammm 265 2010-11-03 07:20:12 Action linked to action_id 265
The strange thing is the action_id, I always get the last date and this is ok, but I’ve also always get the fist action_id instead of the one relative to the correct date row.
Where I’m wrong?
You’re close. Try: