The where
should be before the group by
.
You can also write this using an explicit join
:
SELECT fp.forum_id, COUNT(fp.forum_id) AS num_posts
FROM forums_posts fp join
(SELECT p.forum_id, COUNT(p.post_id) AS num_joined_posts
FROM posts p
WHERE p.post_type IN ('TypeA', 'TypeB', 'TypeC')
group by p.forum_id
) p
on p.forum_id = fp.forum_id
GROUP BY fp.forum_id
ORDER BY num_posts DESC
Although, I'm thinking the most efficient rendition might be:
SELECT fp.forum_id, COUNT(fp.forum_id) AS num_posts
FROM forums_posts fp join
GROUP BY fp.forum_id
having exists (select 1
FROM posts p
WHERE p.post_type IN ('TypeA', 'TypeB', 'TypeC') and
p.forum_id = pf.forum_id
limit 1
)
ORDER BY num_posts DESC
Particularly if you have an index on posts(forum_id, post_type). I move the condition to the having
clause from a where
clause because there is presumably less data for this comparison after the grouping.