sql query that would return a table, and count other tables relevant to the results of the first

StackOverflow https://stackoverflow.com/questions/21242502

  •  30-09-2022
  •  | 
  •  

Question

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:

  1. forums (forum_id,forum_title,forum_description)
  2. topics (topic_id,forum_id(the forum that it belongs to), topic_content...etc)
  3. 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?

Was it helpful?

Solution

The problem can be is that 10 posts relates to one article and article id is coming 10 times with each post so i guess you need to count distinct article ids

SELECT
`forums`.*,
COUNT(DISTINCT `topics`.`topic_id`) AS `num_of_topics`,
COUNT(DISTINCT `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`
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top