GROUP BY is intended for use with aggregation functions; otherwise, it arbitrarily selects one row for each group. Your solution (above and in your own answer) works because MySQL seems to keep the first row of each group, but you cannot guarantee that this will always happen.
You can get the date of the last comment for each post_id
like this.
select post_id, MAX(datetime) as latest from post_comments group by post_id
Use it to select the last comment:
SELECT t1.* FROM post_comments AS t1 JOIN ( SELECT post_id, MAX(datetime) AS latest FROM post_comments GROUP BY post_id ) AS t2 ON t1.post_id = t2.post_id AND t1.datetime = t2.latest
source share