分组并获取每组的最新行

时间:2015-02-23 02:47:53

标签: mysql sql group-by sql-order-by

我想只返回具有不同video_id的最新行。 无论我尝试哪种方式,我一直无法使用它......我之前已经完成了这项工作并没有那么困难但是由于某些原因我的特定查询无效。

我的表/结果:

enter image description here

我一直在尝试这个:

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

2 个答案:

答案 0 :(得分:1)

您在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

答案 1 :(得分:0)

试试这个:

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