views:

199

answers:

3
SELECT user_id, created FROM photo_comments GROUP BY user_id

returns

  user_id  created  
  1        2009-10-20 21:08:22 
  12       2009-10-20 21:45:00 
  16       2009-10-28 20:35:30

But that created date of 2009-10-20 for user id 1 is the first entry by user id 1.

How can I get the last entry by user id 1? (date should be 2009-11-02)

I'm trying to get the last entry by each user in order of most recent first.

+3  A: 

This will work:

SELECT user_id, max(created) FROM photo_comments GROUP BY user_id
Anthony Conyers
In this version, you can't add other fields (like `photo_id` or `comment_id`) into the query and expect them to work sensibly.
Ken Bloom
just add `ORDER BY max(created) DESC` to the end
Ty W
A: 

does SELECT user_id, created FROM photo_comments order by created desc GROUP BY user_id

not work?

markj9
It orders the result set, so the example set I posted is listed in reverse order, still doesn't get the most recent entries.
Jack B Nimble
+1  A: 

Ordinary SQL isn't supposed to allow that sort of query in the first place. In theory, you can only request a field that you named in a GROUP BY clause or an aggregate function of some other field. Here's how you'd build your modified query. (Then you can add other fields too on the first line.)

SELECT user_id, created
FROM photo_comments o
WHERE created =
    (SELECT MAX(created) 
    FROM photo_comments i
    WHERE o.user_id=i.user_id)
Ken Bloom
This is the best way, in my opinion.
j.a.estevan
mysql doesn't seem to care for your inner and outer. 'Error in your SQL syntax near "outer"'
Jack B Nimble
`outer` and `inner` are keywords used with joins. I usually remember this little detail the first time I run the query and get the syntax error. I've fixed the answer now by renaming them `o` and `i`.
Ken Bloom
I added 'order by created DESC' to get the exact result I was looking for.
Jack B Nimble