Используйте этот запрос:
select p.post_id, count(c.id) as total_comments
from posts p LEFT JOIN comments c
on p.post_id = c.id
group by p.post_id
order by p.post_id desc;
Иллюстрация:
select * from posts;
+----------+---------+
| postdesc | post_id |
+----------+---------+
| post-1 | 1 |
| post-2 | 2 |
| post-3 | 3 |
+----------+---------+
select * from comments;
+--------------+------+------------+
| comment_desc | id | created_at |
+--------------+------+------------+
| comment-1 | 1 | 2018-04-01 |
| comment-2 | 1 | 2018-04-02 |
| comment-3 | 2 | 2018-04-03 |
| comment-4 | 1 | 2018-04-04 |
+--------------+------+------------+
--query
+---------+----------------+
| post_id | total_comments |
+---------+----------------+
| 3 | 0 |
| 2 | 1 |
| 1 | 3 |
+---------+----------------+
Обновление : эта версия не использует синтаксис JOIN. Дает тот же результат, что и выше.
select a.post_id, a.total_comments
from
(
select post_id, 0 as total_comments
from posts
where post_id not in
(
select distinct id
from comments
)
union
select id, count(*)
from comments
group by id
) a
order by a.post_id desc;