2013-02-13 86 views
3

我正在努力爲以下問題找到最佳解決方案。 假設我有一個這樣的表「表」:每個指定組選擇n個隨機行

id name report_id 
1 name1 1 
2 name2 3 
3 name3 5 
4 name1 7 
5 name3 8 
.................... 

我想選擇一組每個值:(「名稱1」,「名2」)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個隨機記錄 - 這個查詢將是有點大。

感謝很多提前

+0

看看這個http://stackoverflow.com/questions/14245275/mysql-select-one-random-record-from-each-category – 2013-02-13 13:17:55

回答

3

SQLFiddle demo

select ID,NAME,REPORT_ID 
from 
(
select *, @row:=if([email protected],@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

謝謝,Valex。這是一個非常明確的解決方案! – 2013-02-13 15:54:52

+0

@RedBaron這兩個查詢都會生成相同的計劃。 – 2013-02-13 16:49:11

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

+0

非常感謝,哈姆雷特。這正是我所期待的。 – 2013-02-13 13:31:32

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 

我有同樣的問題,並從同事找到了這個答案。