我有一张这样的表:
+--------+--------+
| 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 |
+--------+--------+
提前致谢!
最佳答案
这是一个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 - 获取每个列值的前 N 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12105893/