1

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?

1 Answer 1

2
SELECT `categories`.`id`, `categories`.`name`,
   COUNT(DISTINCT topics.id) as topics,
   COUNT(DISTINCT posts.id) as posts
FROM `categories` 
LEFT JOIN `topics` ON `categories`.`id` = `topics`.`categoryid` 
LEFT JOIN `posts` ON `topics`.`id` = `posts`.`topicid`
GROUP BY categories.id

... but getting all the posts & topics involved may be heavy on the server. I'd cache it somethere for a little while.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'll keep that in mind, though I don't expect much activity at all for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.