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

前端 未结 5 676
醉话见心
醉话见心 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:49

    Maybe not the best way of doing it but sometimes the function group_concat() can be userfull, it will return a string of all aggregated values sorted like you want and seperated by comma (coupled value are separated by space). I then use the function SPLIT_STRING() to cut the first id in the string.

    SELECT  
    post_id, 
    SPLIT_STRING( group_concat( forum_id, post_time ORDER BY post_time DESC ) ,' ',1 )as forum_id, 
    SPLIT_STRING( group_concat( topic_id, post_time ORDER BY post_time DESC ) ,' ',1 )as topic_id ,
    FROM posts 
    GROUP BY topic_id 
    ORDER BY post_time DESC
    LIMIT 5
    

    So the aggregated forum_id, post_time will be like this :

    81 2012-11-19 06:59:04,83 2012-11-19 16:07:46

    So you need to work with a string representation of integers and datetime couples, each couples separated by comma so I used this function to get the first INT :

    CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT)
    RETURNS VARCHAR(255)
    RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
           LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
           delim, '');
    

    Note : function SPLIT_STRING(str, delim, pos) was found here : Equivalent of explode() to work with strings in MySQL

提交回复
热议问题