php mysql Group By to get latest record, not first record

前端 未结 5 675
醉话见心
醉话见心 2020-12-05 15:04

The Table:

(`post_id`, `forum_id`, `topic_id`, `post_time`) 
(79, 8, 4, \'2012-11-19 06:58:08\');
(80, 3, 3, \'2012-11-19 06:58:42\'),
(81, 9, 9, \'2012-11-1         


        
5条回答
  •  北海茫月
    2020-12-05 15:44

    If you select attributes that are not used in the group clause, and are not aggregates, the result is unspecified. I.e you don't know which rows the other attributes are selected from. (The sql standard does not allow such queries, but MySQL is more relaxed).

    The query should then be written e.g. as

    SELECT post_id, forum_id, topic_id
    FROM posts p
    WHERE post_time =
      (SELECT max(post_time) FROM posts p2
       WHERE p2.topic_id = p.topic_id
       AND p2.forum_id = p.forum_id)
    GROUP BY forum_id, topic_id, post_id
    ORDER BY post_time DESC
    LIMIT 5;
    

    or

    SELECT post_id, forum_id, topic_id FROM posts
    NATURAL JOIN
    (SELECT forum_id, topic_id, max(post_time) AS post_time
     FROM posts
     GROUP BY forum_id, topic_id) p
    ORDER BY post_time
    LIMIT 5;
    

提交回复
热议问题