我有两个表,博客和帖子,它们之间具有预期的关系。帖子可以发布或草稿。我想选择所有具有已发布和草稿帖子计数的博客。我该怎么做?
我试过这个查询:
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
但我最终得到了两个published_post_count 和draft_post_count 相同的数字,并且两者都是错误的。
然后我绝望并尝试:
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
但在这两种情况下,我都有相同的错误结果。
这样做的正确方法是什么?
谢谢。