I have 2 tables one is for articles and second is for comments, now I want to get total number of comments and all articles details using 1 query, I dont want to use 2 queries one separately for article details and one for comments, can someone please help me get total number of comments on a specific article and all its comments..
article table… article_id
comments table…. comment_id, comment_article_id
normal to get comments I so
SELECT COUNT(*) as total ….
now I want to get both thing (full articles details from article_id) and from comments table total number of comments (and if possible all comments details on that article ID) with only one query…
regards
To get the article details and number of comments you can use the following
You can’t really get the comment details in the same query as the articles table due to the fact that the two will most likely have different fields. If you would really like to just get the article followed by all comments then something like the following would work. With the following, make sure that the columns in the first query match the columns in the second (i.e. the title column from the article matches either an empty string (shown) or a title column from the comments). I would personally not do this, and instead would just do 2 queries, one to get the article details and one to get any comments as that way it doesn’t matter that the column types may not match, and it also means the articles query doesn’t need joining onto comments as you can just count the number of rows that are in the comments query
Single query union method, not advised
2-query method, simpler and in most cases more efficient