MySQL分组查询,随机从各分组取要求行数的数据,数据表结构如下:
按class分组,各分组随机取2条数据,sql如下:
truncate table tmp;
insert into tmp (id,name,class,score) select * from test order by class,rand();
select a.* from tmp a where (select count(*) from tmp b where b.class=a.class and b.r>a.r)<2;