SQL 99 answer.
Re: Find the maximum value of a column and return the corresponding id?
Answer by: PFC
(http://article.gmane.org/gmane.comp.db.postgresql.sql/16285)
If you want the latest by user, you can cheat a bit and use the fact that the id's are incrementing, thus ordering by the id is about the same as ordering by the date field. I know it can be inexact in some corner cases, but it's a good approximation, and very useful in practice :
[sql]
SELECT user_id, max(note_id) FROM notes GROUP by user_id;
[/sql]
So :
[sql]
SELECT * FROM notes WHERE id IN (SELECT max(note_id) FROM notes GROUP by user_id) ;
[/sql]
|