I have a simple articles and comments table. I want to display the articles along with their comments. I want to union with one select with the comments and another select without the comments on the same table. I have article number 1 with 1 comment and article number 2 with no comments and article number 3 with 2 comments.
The articles table:
articles.id | articles.content
1 | test article
2 | test another
3 | test third
The comments table:
comments.id | comments.aid | comments.comment
1 | 1 | bad one
2 | 3 | very good
3 | 3 | good
I use the following query to get the results.
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
The result I get which is correct:
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
Now if I want to count the comments also I add COUNT to the query and it becomes:
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
Now the results change after adding the the count column and not all rows are outputted:
article_id | comment_id | comment | count_comments
3 | NULL | NULL | NULL
2 | NULL | NULL | NULL
1 | NULL | NULL | NULL
1 | 1 | bad one | 3
Now the comments aren’t displayed except the comment of article 1, ID(2) should be displayed twice for the 2 select commands, and ID(3) should be displayed 3 times (1 for the second select command and 2 for the first select commands as there are 2 comments)
The correct results that I expect:
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
I don’t know why adding count leads to ths.
Thanks
When you add the
count()it affects only the first subquery. So, that subquery is only returning one row rather than multiple rows.I’m having problems uploading SQL today, but I think you want something in this form:
I assume that you are trying to get all articles included. You don’t need the
union all. Your first query is sufficient (because of theleft join):In the results that you say are correct, you have two rows for article 2, both with NULLs. Is this really what you want? If you want to add that, then put this before the
order by: