I'm trying to write a forum for a school project, and I'm still struggling with some queries. So, basically I have the following tables:
- forums (forum_id,forum_title,forum_description)
- topics (topic_id,forum_id(the forum that it belongs to), topic_content...etc)
- posts (post_id, topic_id(the topic that it belongs to)...etc)
What I need is a query that would display all the forums in the main page + count all the topics and add it alongside the relevant forum AND also count all the posts that belong to all the topics that belong to the relevant forum.
This is what I came up with so far:
SELECT
`forums`.*,
COUNT(`topics`.`topic_id`) AS `num_of_topics`,
COUNT(`posts`.`post_id`) AS `num_of_posts`
FROM `forums`
LEFT JOIN `topics` ON `topics`.`forum_id` = `forums`.`forum_id`
LEFT JOIN `posts` ON `posts`.`topic_id` = `topics`.`topic_id`
GROUP BY `forums`.`forum_id`
For some reason, this query returns rather peculiar values. When there's one topic and no posts that belong to this topic, it correctly returns 1 for topics and 0 for posts. However, when I add more relevant posts, it increases the number of topics as well. Basically, it equates the number of topics to the number of posts so I always get x topics and x posts if post is greater than 0.
Any ideas?