So, when you do this (this is what you do, reformulated for JOIN):
SELECT post.post_id, COUNT(comment) FROM `comment` INNER JOIN post ON `comment`.post_id = post.post_id GROUP BY post.post_id;
You only collect posts that have at least one link in the comment.
If you change the JOIN type to LEFT join , as follows:
SELECT post.post_id, COUNT(comment) FROM `comment` LEFT JOIN post ON `comment`.post_id = post.post_id GROUP BY post.post_id;
Then the rows from the column are all there, and NULL values โโare inserted for comment columns if there are no comments associated with this row (this is the left join). Therefore, if the comment is a column from the table comment, it will be present for each row of the column table, but with a NULL value, after the group in the post_id column, the subset of comments associated with this message contains only 1 NULL, the counter should return 0.
select count(NULL);
returns 0.
Now you can use a subquery, but this is a really bad idea, subqueries are usually executed instead of LEFT JOINS, usually this is an error , sometimes it is not, but in fact it is often an error. When you make left join indexes, they are used to compare the key values โโof two tables (the ON clause) and construct one final โtemporaryโ result of the rows, mix the values โโfrom both tables (and then, or, possibly, at the same time, apply filters from other parts of your requests). When you use a subquery, for each row of the first table, a new query is launched to get the results from the second table (not always, but this is another problem), the cost will be significantly higher for the database engine.