Imagine I have a database with following relational schema:
forums(id, title)
forum_topics(id, forum_id, title, count_views, some_data)
forum_posts(id, topic_id, title, content, author_id, another_data)
And say I have two rows in the forums_posts table with the data:
(1, 1, 'some title', 'some content', 4, 'blahr')
(2, 1, 'another post title', 'my content', 5, 'nah')
Now, I want to create a SQL Statement which will give me the topic id, count of posts for that topic AND the user id of the latest contributor to the topic. It’s obviously not a problem to get the first two values while the latter is pretty tricky. Here’s what I have so far:
SELECT topic_id,
COUNT(*) AS count_posts,
forum_posts.author_id AS last_answer_by
FROM forum_posts
JOIN forum_topics ON forum_posts.topic_id = forum_topics.id
GROUP BY topic_id
The query given above will give me, assumed there is a forum_topics entry with id = 1:
topic_id = 1
count_posts = 2
last_answer_by = 4
While assuming a higher post id means it has been written later than a post entry with a lower id what I want to get is:
topic_id = 1
count_posts = 2
last_answer_by = 5
You only need to query against the forum_posts table to get the results you want but you need to use a subquery in your from clause to first obtain the count of the number of posts for each topic_id in the forum_posts table along with the maximum post id for the topic. You then join the results of that subquery back to the original forum_posts table on that maximum post id: