这是使用的一种方法
UNIOn ALL(请参阅带有演示的SQL
Fiddle)。这适用于两个组,如果您有两个以上的组,则需要指定
group数字并为每个组添加查询
group:
( select * from mytable where `group` = 1 order by age desc LIMIT 2)UNIOn ALL( select * from mytable where `group` = 2 order by age desc LIMIT 2)
有多种方法可以执行此操作,请参阅本文以确定适合您情况的最佳路线:
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-
group-in-sql/
编辑:
这也可能对您有用,它会为每个记录生成一个行号。使用上面链接中的示例,这将仅返回行号小于或等于2的那些记录:
select person, `group`, agefrom ( select person, `group`, age, (@num:=if(@group = `group`, @num +1, if(@group := `group`, 1, 1))) row_number from test t CROSS JOIN (select @num:=0, @group:=null) c order by `Group`, Age desc, person) as x where x.row_number <= 2;
观看演示



