I have two tables, blogs and posts, with the expected relationship between them. Posts can be published or draft. I want to select all blogs with the counts of published and draft posts. How can I do it?
I tried this query:
SELECT blogs.*,
COUNT(published_posts.*) AS published_post_count,
COUNT(draft_posts.*) AS draft_post_count
FROM blogs
JOIN posts AS published_posts ON published_posts.blog_id=blogs.id AND
published_posts.state = "published"
JOIN posts AS draft_posts ON draft_posts.blog_id=blogs.id AND
draft_posts.state = "draft"
GROUP BY blogs.id
but I end up with the same number for both published_post_count and draft_post_count and being wrong for both.
Then I got desperate and trie:
SELECT blogs.*,
COUNT(published_posts.*) AS published_post_count,
COUNT(draft_posts.*) AS draft_post_count
FROM blogs
JOIN (SELECT * FROM posts WHERE posts.state="published") AS published_posts
ON published_posts.blog_id=blogs.id
JOIN (SELECT * FROM posts WHERE posts.state="draft") AS draft_posts
ON draft_posts.blog_id=blogs.id
GROUP BY blogs.id
but in both cases I had the same wrong results.
What’s the proper way to do this?
Thanks.
If you are just interested in the
COUNTand you are alsoJOINing the tables. So there has to be one or morepostthat has beenpublishedand one or more that isdraft. So maybe this will help you: