Jump to content

Selecting most recent by Timestamp


cg5572

Recommended Posts

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?

Link to comment
Share on other sites

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')

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.