如何从表中获取最后3条记录

时间:2012-06-26 09:51:25

标签: mysql

我有一个包含以下字段和数据的表:

uid     message         created
======= =============== ==========
1       text1           1305244929
2       text2           1305244930
3       text3           1305244931
1       text4           1305244932
1       text5           1305244933
3       text6           1305244934
2       text7           1305244945
1       text8           1305244956
3       text9           1305244947
1       text10          1305244948
2       text11          1305244967
1       text12          1305244968
3       text13          1305244969
1       text14          1305244970
2       text15          1305244971
3       text16          1305244972
3       text17          1305244973

如何按创建的

为每个 uid订购的DESC获取最后3条记录

1 个答案:

答案 0 :(得分:0)

这未经过测试,但应该可以解决问题:

SELECT uid, message, created FROM (
SELECT
IF(@prev != q.uid, @rownum:=1, @rownum:=@rownum+1) as rownumber, @prev:=q.uid, q.*
FROM (
    SELECT
    uid, message, created
    FROM yourTable yt
    , (SELECT @rownum:=0, @prev:='') r
    ORDER BY uid, created DESC
)q
)asdf
WHERE asdf.rownumber <= 3

和其他人一样,主键对你的桌子来说很不错。