select n random rows per specified group

前端 未结 3 1629
独厮守ぢ
独厮守ぢ 2020-12-10 19:53

I am struggling to find an optimal solution for the following problem. Suppose I have a table \'Table\' like this:

id    name    report_id
 1    name1    1
          


        
3条回答
  •  孤街浪徒
    2020-12-10 20:38

    SQLFiddle demo

    select ID,NAME,REPORT_ID
    from
    (
    select *, @row:=if(name=@name,@row,0)+1 as rn, @name:=name from 
    (select *,RAND() as trand from t) t1,
    (select @row:=0,@name:='') tm2 
    order by name,trand
    ) t2
    where rn<=10
    

提交回复
热议问题