cg5572 Posted August 17, 2010 Share Posted August 17, 2010 Ok I have a really rookie question which for some reason I can't get my head around: I have a table which stores user comments, with the following fields: - comment_id - post_id - user_id - category_id - timestamp I'm currently using the following query to return all comments by a user in a given category: SELECT * FROM comments_table WHERE user_id='$user' AND category='$category' What I want to be able to do is retrieve the most recent comment for each post, i.e. if the above query returns multiple comments for the same post_id, show only the most recent one (highest timestamp). Is there a way to build this into the query, or if not what is the best way of extracting them in the PHP afterwards? Quote Link to comment https://forums.phpfreaks.com/topic/210964-selecting-most-recent-by-timestamp/ Share on other sites More sharing options...
PFMaBiSmAd Posted August 17, 2010 Share Posted August 17, 2010 http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html Quote Link to comment https://forums.phpfreaks.com/topic/210964-selecting-most-recent-by-timestamp/#findComment-1100356 Share on other sites More sharing options...
cg5572 Posted August 17, 2010 Author Share Posted August 17, 2010 Amazing, thanks! Quote Link to comment https://forums.phpfreaks.com/topic/210964-selecting-most-recent-by-timestamp/#findComment-1100357 Share on other sites More sharing options...
cg5572 Posted August 17, 2010 Author Share Posted August 17, 2010 For anyone who finds this, the final query for this is as follows: SELECT * FROM comments_table s1 WHERE timestamp=(SELECT MAX(s2.timestamp) FROM comments_table s2 WHERE s1.post_id = s2.post_id AND user_id='$user' AND category='$category') Quote Link to comment https://forums.phpfreaks.com/topic/210964-selecting-most-recent-by-timestamp/#findComment-1100437 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.