我正在努力寻找以下问题的最佳解决方案。假设我有一个像这样的表“ Table”:
id name report_id 1 name1 1 2 name2 3 3 name3 5 4 name1 7 5 name3 8 ....................
我想为集合中的每个值选择:(’name1’,’name2’)10个随机唯一行。当然,可以像这样进行联合:
(SELECT * FROM Table WHERE name='name1' ORDER BY RAND() LIMIT 10) UNION (SELECT * FROM Table WHERE name='name2' ORDER BY RAND() LIMIT 10)
但是,如果我有100个唯一的名称,而我必须为其选择10个随机记录,则此查询将有点大。
提前非常感谢
SQLFiddle演示
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