为每个指定的组选择n个随机行

时间:2013-02-13 13:11:23

标签: mysql

我正在努力为以下问题找到最佳解决方案。 假设我有一个像'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个随机记录 - 这个查询会有点大。

提前多多感谢

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

试试这个:

  SELECT
    id, 
    name,
    report_id
  FROM
  (
    SELECT id,
        report_id,
        name,
        CASE WHEN @name != name THEN @rn := 1 ELSE @rn := @rn + 1 END rn,
        @name:=name
     FROM (SELECT * FROM tbl ORDER BY RAND()) a,
        (SELECT @rn:=0, @name := NULL) r
     ORDER BY name
  ) s
  WHERE rn <= 10;

<强> SQL FIDDLE DEMO

答案 2 :(得分:0)

这在mysql中不起作用,但在psql中你可以使用partition by

select name,report_id from
(select name,report_id,row_number()
over
(partition by name order by random())
as rn from Table) a
where rn<=10

我有同样的问题,并从同事那里得到了答案。