0

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

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 的最后 3 条记录,按创建的 DESC 排序

4

1 回答 1

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

就像其他人说的那样,主键对您的表来说会很好。

于 2012-06-26T11:29:36.013 回答