I have a SQL statement that I’m trying to run, but it’s throwing an error:
SELECT fp.forum_id, COUNT(fp.forum_id) AS num_posts
FROM forums_posts fp
GROUP BY fp.forum_id
WHERE (
SELECT COUNT(p.post_id) AS num_joined_posts
FROM posts p
WHERE p.post_type IN ('TypeA', 'TypeB', 'TypeC')
AND p.forum_id = fp.forum_id
) > 0
ORDER BY num_posts DESC
The forums_posts table is a relational table matching forum IDs to post IDs, and the posts table (which also stores the post’s forum ID) just contains info about each post. I am trying to find out: which forums have posts of the type TypeA, TypeB, or TypeC; and how many posts are in each of those forums.
Nested SQL statements have never been my strong suit. Can somebody point out the correct way to go about doing this? Thanks.
The
whereshould be before thegroup by.You can also write this using an explicit
join:Although, I’m thinking the most efficient rendition might be:
Particularly if you have an index on posts(forum_id, post_type). I move the condition to the
havingclause from awhereclause because there is presumably less data for this comparison after the grouping.