Start by using proper join
syntax. Then return appropriate columns. You are aggregating by id_post
so there is only one row for each post. Putting an arbitrary comment on the same row would not (in general) be a sensible thing to do.
The answer to your question, though, is to order by the greatest of the two dates. The two dates are p.creation_date
and `max(c.creation_date).
select P.*, max(P.creation_date)
From posts P left join
comments C
on P.id_post=c.id_post
group by P.id_post
order by greatest(p.creation_date, coalesce(max(c.creation_date), P.post_date));
The coalesce()
is necessary because of the left outer join
; the comment creation date could be NULL
.
EDIT:
If you assume that comments come after posts, you can simplify the order by
to:
order by coalesce(max(c.creation_date), P.post_date);