tags:

views:

798

answers:

6
uid     timestamp
1  1242420497
1  1243534661
1  1243534858
1  1243611312
1  1243611511
3  1244817764
3  1244819093
1  1244749446

I have this table, and I am lookng to grab the row that has the highest time stamp. I tried using

SELECT uid,max(timestamp) FROM `node_revisions` WHERE nid=51

but that returned

uid timestamp
1   1244819093

which has the wrong uid as you can see. How would I make it grab the uid from the correct row? thanks

+4  A: 

You're missing the GROUP BY clause.

SELECT
    uid,
    max(timestamp) as max_time
FROM
    node_revisions
WHERE
    nid = 51
GROUP BY
    uid
ORDER BY 
    max_time DESC 
LIMIT 1
Eric
didnt work, since it also returned the max time of uid = 1
Steven1350
@op: What RDBMS are you using?
Eric
@OP: You could add "ORDER BY max_time DESC LIMIT 1" to the SQL to prevent more than one UID from coming back.
Samir Talwar
@Samir: Good point, added!
Eric
+1  A: 

first thing, nid does not appear in your table.

second, I suspect you want group by uid

Jonathan Fingland
+1  A: 

Your example uses nid=51 instead of uid=51. Is this code copied directly from what you're running? If there is a nid field, this may be your issue. And you need a group by clause.

SELECT uid, max(timestamp) as max_time
FROM 'node_revisions'
WHERE uid = 51
GROUP BY uid
Justin Balvanz
A: 
SELECT uid, timestamp 
FROM node_revisions 
WHERE timestamp = (SELECT MAX(timestamp) FROM node_revisions);

Updated per Ryan Oberoi's comment; since we're getting just the one record, MAX() in the outer query is unnecessary. Thanks.

Carl Manaster
thanks, that seems to work. I just added that NID field to it to meet my needs, but it got the job done
Steven1350
do not need the MAX in the first select... simpler to use ORDER BY timestamp DESC...
Ryan Oberoi
ryan is right...see my answer below.
Eric
+3  A: 

SELECT * FROM node_revisions WHERE nid=51 ORDER BY timestamp DESC LIMIT 1

Ryan Oberoi
A: 

This will work just fine..im sure

select uid FROM `node_revisions`
WHERE uid=51 and timestamp = (select max(timestamp) where uid = 51)
group by uid
Eric