且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取每组分组结果的前n条记录

更新时间:2021-08-01 22:24:28

这是使用UNION ALL的一种方法(请参阅

Here is one way to do this, using UNION ALL (See SQL Fiddle with Demo). This works with two groups, if you have more than two groups, then you would need to specify the group number and add queries for each 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
)

有多种方法可以执行此操作,请参阅本文以确定适合您情况的***路线:

There are a variety of ways to do this, see this article to determine the best route for your situation:

这可能也对您有用,它会为每条记录生成一个行号.使用上面链接中的示例,这将仅返回行号小于或等于2的那些记录:

This might work for you too, it generates a row number for each record. Using an example from the link above this will return only those records with a row number of less than or equal to 2:

select person, `group`, age
from 
(
   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;

请参见演示