2

我有两个表,博客和帖子,它们之间具有预期的关系。帖子可以发布或草稿。我想选择所有具有已发布和草稿帖子计数的博客。我该怎么做?

我试过这个查询:

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

但在这两种情况下,我都有相同的错误结果。

这样做的正确方法是什么?

谢谢。

4

3 回答 3

4

如果您只是对 the 感兴趣COUNT并且您也在JOINing 表格。所以必须有一个或多个post已经存在published和一个或多个存在draft。所以也许这会对你有所帮助:

SELECT blogs.*,
       (
            SELECT COUNT(*)
            FROM posts
            WHERE posts.blog_id=blogs.id
            AND posts.state = "published"
       ) AS published_post_count,
       (
            SELECT COUNT(*)
            FROM posts
            WHERE posts.blog_id=blogs.id
            AND posts.state = "draft"
       ) AS draft_post_count,
FROM blogs
于 2012-04-05T12:04:56.460 回答
2

您可能会计算不同的状态并重新加入博客:

SELECT blogs.*, p.published_post_count, p.draft_post_count
FROM blogs
JOIN 
(
  SELECT posts.blog_id,
         SUM(case when posts.state = 'published' then 1 end) 
             AS published_post_count,
         SUM(case when posts.state = 'draft' then 1 end) 
             AS draft_post_count
    FROM posts
   GROUP BY blog_id
) p
ON p.blog_id=blogs.id
于 2012-04-05T12:12:39.017 回答
1

尝试 :

GROUP BY blogs.id,published_posts.[theKeyOfThisTable],draft_posts.[theKeyOfThisTable]

因为您应该在“分组依据”子句中包含“选择”的列

于 2012-04-05T12:08:43.203 回答