MYSQL分组获取组内排行并取前几条

select team_id, host_id, rank1, p
from (
select t.team_id ,t.host_id,
if(@p=t.team_id ,@r := @r+1,@r := 1) as rank1, (@p := t.team_id ) as p
from t_team_member t, (select @p := null, @r := 1) a 
where t.team_id in (2,3,4,5,6) order by team_id 
) w
where w.rank1 <=6

需求:按团队ID分组,每组取6条记录

你可能感兴趣的:(mysql,sql,数据库)