分组并从每个组中获取最新行

Group by and get the latest row from each group

我只想 return 具有不同 video_id 的最新行。 无论我尝试哪种方式,我都无法让它工作......我以前做过这个并且并不那么困难但是由于某种原因我的特定查询将无法工作。

我的table/results:

我一直在尝试这个:

SELECT * FROM user_video_history 
WHERE `user_id` = $db_safe_user_id 
GROUP BY video_id 
ORDER BY `date` DESC LIMIT 3

我也试过这个:

SELECT *
FROM (SELECT *
        FROM user_video_history
        WHERE `user_id` = $db_safe_user_id
        ORDER BY `date` DESC) 
GROUP BY `video_id`
ORDER BY `date` DESC

试试这个:

SELECT 
    t1 . *
FROM
    user_video_history t1
        JOIN
    (SELECT 
        id, MAX(`date`) `date`
    FROM
        user_video_history
    GROUP BY user_id) t2 ON t1.user_id = t2.user_id
        AND t1.`date` = t2.`date`
    LIMIT 3

当 GROUP BY

时不能使用 select *

试试这个...

SELECT 
    A . *
FROM
    user_video_history A,
    (SELECT 
        video_id, max(date) maxdate
    FROM
        user_video_history
    WHERE
        `user_id` = $db_safe_user_id
    GROUP BY video_id) B
where
    A.video_id = B.video_id
        and A.date = B.maxdate
order by A.date DESC
limit 3