2012-08-24 75 views
1

我有這樣的一個表:獲得前N個結果爲每列值

+--------+--------+ 
| name | kind | 
+--------+--------+ 
| cat | animal | 
| dog | animal | 
| horse | animal | 
| ant | animal | 
| bird | animal | 
| tree | plant | 
| grass | plant | 
| carrot | plant | 
|     | 
|  ... etc. | 
+--------+--------+ 

我怎樣才能得到每個的前N個項目?例如。 N = 2:

+--------+--------+ 
| name | kind | 
+--------+--------+ 
| ant | animal | 
| bird | animal | 
| carrot | plant | 
| grass | plant | 
+--------+--------+ 

在此先感謝!

+0

可能重複(http://stackoverflow.com/questions/1895110/row-number-in-mysql) – podiluska

回答

3

這裏是一個SqlFiddle demo

select name,kind from 
(

select Name,Kind, 
     @i:=if(@kind=kind,@i+1,1) rn, 
     @kind:=kind 
     from t, (select @i:=0,@kind:='') d 
     order by Kind,name 
) t1 
where t1.rn<=2 
    order by Kind,name 
的[在MySQL ROW_NUMBER()]
+0

這並未」 t套件爲我的約1M記錄。 ORDER BY需要很多時間。 –

+0

它比獲取所有結果和在PHP中過濾TOP N更慢...... –

+0

我認爲你可以排除最新的'order by',因爲嵌套查詢已經排序,所以我認爲MySql將輸出這個查詢,而不需要子查詢順序改變。你也應該使用複雜的Kind和Name索引來索引你的表。 – valex