MySQL Select By Newest Timestamp

Viewed 82074

I've seen some similar types of questions on SO, however, I have not been able to find a solution to my specific issue. (FYI, these are not my real columns, just a shortened example).

I have a basic table my_table:

user_1 user_2 timestamp note(not part of table)
23 25 2012-08-10 22:00:00
24 22 2012-08-10 19:00:00 <=== I would like to return this row
24 22 2012-08-10 17:00:00
21 17 2012-08-10 15:00:00

So, what I want to do is be able to:

 1) Select the "newest" row, based on timestamp AND 
 2) Select the 'user_2' column when given a value.  

I have tried something like:

 SELECT *
 FROM my_table
 WHERE user_2 = 22
 AND timestamp = (
 SELECT MAX( timestamp )
 FROM my_table )
 LIMIT 1 

But this does not return the row I am looking for. Any help on fixing this query would be great.

Thanks very much.

4 Answers
Related