我有一张这样的桌子:
+--------+--------+
| 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 :(得分:3)
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