I'm making a message board and am trying to construct a query. My database structure is as follows:
Table name: table row, table row
categories: id, name
topics: id, categoryid
posts: id, topicid
On the homepage I'd like to list out each category and the number of topics and number of posts in each category. I've looked at some queries that use multiple joins but I'm having trouble applying the syntax to my situation.
Here's what I've come up with:
SELECT `categories`.`id`, `categories`.`name`,
SELECT COUNT(DISTINCT `topics`.`id`)
FROM `topics`
WHERE `topics`.`categoryid` = `categories`.`id`
AS `numtopics`,
SELECT COUNT(DISTINCT `posts`.`id`)
FROM `posts`
WHERE `posts`topicid` = `topics`.`id`
AS `numposts`
FROM `categories`
JOIN `topics` ON `categories`.`id` = `topics`.`categoryid`
JOIN `posts` ON `topics`.`id` = `posts`.`topicid`
;
I start to get confused when I try to count the number of posts based on the topicid and then join that with the table created by the first join. Is it possible to do what I'm doing? If so, am I going about it correctly?