MySQL retrieve latest record for Group

北慕城南 提交于 2019-11-29 07:17:28
alexis

GROUP BY is intended to be used with aggregating functions, otherwise it arbitrarily selects one row per group. Your solution (above and in your self-answer) works because MySQL seems to be keeping the first row of each group, but you're not guaranteed that this will always happen.

You can get the date of the latest 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 latest 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

As so many questions come in with "I want the latest entry for...", and have some date time. If the table in question is auto-increment, and the date/time stamp will ALWAYS stay in sequential time correlation ... i.e.: the user has no chance to edit or otherwise change the timestamp on the record to put today's entry with a date of 3 weeks ago... so many will keep trying to get that last date and re-join on a non-advantaged key. Just get the maximum ID key for the post and use that... I would have an index on the post ID and the primary auto-increment key.

select
      P2.*
   from
      ( select post_id, max( post_comment_id ) as LastPost
           from post_comments
           group by post_id ) LastPerPost
         JOIN post_comments P2
            on LastPerPost.LastPost = P2.post_comment_id

Sorted it! I did it like this:

SELECT * FROM (
    SELECT * FROM post_comments ORDER BY datetime DESC
) AS post_comments 
GROUP BY post_id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!