UNION ALL中的COUNT会导致跳过预期结果


COUNT inside UNION ALL leads to skipping expected results

我有一个简单的文章和注释表。我想把文章和他们的评论一起展示出来。我想在同一个表上合并一个带注释的select和另一个不带注释的select。我有第1篇有1条评论,第2篇没有评论,第3篇有2条评论。

文章表:

articles.id | articles.content
   1        |  test article
   2        |  test another
   3        |   test third

评论表:

comments.id | comments.aid | comments.comment
  1         |   1          |  bad one
  2         |   3          |  very good
  3         |   3          |   good          

我使用以下查询来获得结果。

SELECT articles.id AS article_id,
comments.id AS comment_id,
comment
FROM articles
LEFT JOIN comments ON comments.aid = articles.id
UNION ALL
SELECT articles.id AS article_id,
NULL,
NULL
FROM articles
GROUP BY article_id
ORDER BY article_id DESC

我得到的结果是正确的:

article_id | comment_id | comment
   3       | 3          | good
   3       | 2          | very good
   3       | NULL       | NULL
   2       | NULL       | NULL
   2       | NULL       | NULL
   1       | NULL       | NULL
   1       | 1          | bad one

现在,如果我想计算评论,我也会在查询中添加count,它变成:

SELECT articles.id AS article_id,
comments.id AS comment_id,
comment ,
COUNT(DISTINCT comments.id) AS count_comments
FROM articles
LEFT JOIN comments ON comments.aid = articles.id
UNION ALL
SELECT articles.id AS article_id,
NULL,
NULL ,
NULL
FROM articles
GROUP BY article_id
ORDER BY article_id DESC

现在,在添加计数列后,结果会发生变化,并且并非所有行都会输出:

article_id | comment_id | comment   | count_comments
  3        | NULL       | NULL      |  NULL
  2        | NULL       | NULL      |  NULL  
  1        | NULL       | NULL      |  NULL
  1        | 1          | bad one   |  3 

现在,除了文章1的评论之外,不显示评论,ID(2)应该为2个选择命令显示两次,ID(3)应该显示3次(第二个选择命令1次,第一个选择命令2次,因为有2个评论)

我期望的正确结果:

article_id | comment_id | comment   | count_comments
   3       | 3          | good      |   2 
   3       | 2          | very good |   2
   3       | NULL       | NULL      |   NULL  
   2       | NULL       | NULL      |   NULL
   2       | NULL       | NULL      |   NULL
   1       | NULL       | NULL      |   NULL 
   1       | 1          | bad one   |    1

我不知道为什么加上count会导致ths。

感谢

添加count()时,它只影响第一个子查询。因此,该子查询只返回一行,而不是多行。

我今天在上传SQL时遇到了问题,但我想你想要这种形式的东西:

select articles.id AS article_id, comments.id AS comment_id, comment,
       COUNT(DISTINCT comments.id) AS count_comments
from ((subquery1) union all
      (subquery2)
     ) t
group by article_id
order by article_id desc

我想你是想把所有的文章都包括在内。你不需要union all。您的第一个查询就足够了(因为left join):

select articles.id AS article_id, comments.id AS comment_id, comment,
       COUNT(DISTINCT comments.id) AS count_comments
from articles left join
     LEFT JOIN comments ON comments.aid = articles.id
group by article_id
ORDER BY article_id DESC

在您认为正确的结果中,文章2有两行,都有NULL。这真的是你想要的吗?如果你想添加它,那么把它放在order by:之前

union all
select distinct article_id, NULL, NULL, NULL
from articles