Suppose we have two tables. Post and Comment. Post has many Comments. Pretend they are somewhat filled so that the number of comments per post is varied. I want a query which will grab all posts but only the newest comment per post.
I have been directed to joins and sub queries but I can’t figure it out.
Example Output:
Post1:
Comment4 (newest for post1)
Post2:
Comment2 (newest for post2)
Post3:
Comment 10 (newest for post3)
etc…
Any help would be greatly appreciated. Thanks.
This answer assumes that you have a unique identifier for each comment, and that it’s an increasing number. That is, later posts have higher numbers than earlier posts. Doesn’t have to be sequential, just have to be corresponding to order of input.
First, do a query that extracts the maximum comment id, grouped by post id.
Something like this:
This will give you a list of post id’s, and the highest (latest) comment id for each one.
Then you join with this, to extract the rest of the data from the comments, for those id’s.
Then, you join with the posts, to get the information about those posts.
An alternate approach doesn’t use the PostID of the inner query at all. First, pick out the maximum comment id for all unique posts, but don’t care about which post, we know they’re unique.
Then do an IN clause, to get the rest of the data for those comments:
Then simply join in the posts: