2012-06-26 13 views
0

獲得最後3個記錄我有一個表具有以下字段和數據:如何從表

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 

如何獲得最後3個記錄每個 UID下令DESC通過創建

+2

理想情況下,無論這張表應該有它自己的「ID」列,保持關係(如果你設計得當),並讓事情像你想做的事情一樣簡單:) – Brian

+0

我認爲你的表需要一個主鍵。 –

回答

0

這是沒有經過測試,但它應該做的伎倆:

SELECT uid, message, created FROM (
SELECT 
IF(@prev != q.uid, @rownum:=1, @rownum:[email protected]+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 

和其他人一樣,一個主鍵會對你的表很好。

+0

對於一張大桌子,需要很長時間才能收到結果。也許可以找到一個更好的解決方案 –

+0

把一個組合索引(uid,創建),看看是否有幫助。如果沒有你改變你的數據庫模式,我懷疑還有另一種方法來加速這個過程。 – fancyPants

+0

@BoiculeseIuli你有沒有試過把索引放在列上?任何反饋? – fancyPants