2016-07-22 118 views
2

可以說我有如下表:獲取最新的N記錄爲每組

id coulmn_id value date 
1  10  'a'  2016-04-01 
1  11  'b'  2015-10-02 
1  12  'a'  2016-07-03 
1  13  'a'  2015-11-11 
2  11  'c'  2016-01-10 
2  23  'd'  2016-01-11 
3  11  'c'  2016-01-09 
3  111  'd'  2016-01-11 
3  222  'c'  2016-01-10 
3  333  'd'  2016-01-11 

n = 3時,我想獲得最新的n條記錄< = 3每個ID。因此,我將有以下的輸出:

id column_id value date 
1  10  'a'  2016-04-01 
1  12  'a'  2016-07-03 
1  13  'a'  2015-11-11 
2  11  'c'  2016-01-10 
2  23  'd'  2016-01-11 
3  111  'd'  2016-01-11 
3  222  'c'  2016-01-10 
3  333  'd'  2016-01-11 
+0

http://stackoverflow.com/questions/12113699/爲每組分組結果得到最多n個記錄結果 – bill

+1

你的主鍵是什麼? – Strawberry

+0

以上問題的解決方案適用於有限數量的'group_name',日期字段可能很大。 – futurenext110

回答

3

我回答因爲引用的問題具有不穩定的答案(我將有評論)。

下面是應該工作的解決方案:

select t.* 
from (select t.*, 
      (@rn := if(@id = id, @rn + 1, 
         if(@id := id, 1, 1) 
         ) 
      ) as seqnum 
     from t cross join 
      (select @rn := 0, @id := -1) params 
     order by id, date desc 
    ) t 
where seqnum <= 3; 

的差異在溶液是變量分配是在一個單一的表達。 MySQL不保證表達式評估的順序,所以如果代碼要一致地工作,這是非常重要的。

+0

我不是故意跨越這種類型的多個答案,這是更多的問題海報需要解決的問題,但從技術上講,如果'日期'字段不是唯一的,這個答案可能不穩定。 _只需添加一個好的答案._ – Uueerdo

+0

@Uueerdo。 。 。這是一個合理的觀察。但是,除非* data *有問題,否則答案是正確的。從* database *的角度來看,引用的答案可能不正確。 –

0

你可以使用變量來做到這一點。先通過以相反的順序的結果,並分配一個行號,然後過濾結果爲行號小於或等於3,並且重新排序:

select id, value, date 
from  (
      select  id, value, date, 
         @rn := if(@id = id, @rn+1, if (@id := id, 1, 1)) rn 
      from  mytable, 
      cross join (@id := null, @rn := null) init 
      order by id, date desc 
     ) as base 
where rn <= 3 
order by id, date asc