2017-03-07 60 views
-1
Table Name : Employee 
    +------+------+ 
    | name | dept | 
    +------+------+ 
    | ABC | 1 | 
    | BCA | 1 | 
    | CYZ | 2 | 
    | CYZ | 1 | 
    | n... | n... | 
    +------+------+ 

Table Name : Department 
    +----+-----------+ 
    | id | dept_name | 
    +----+-----------+ 
    | 1 | YYY  | 
    | 2 | ZZZ  | 
    | 3 | DDD  | 
    +----+-----------+ 

我必須從表Employees的每個dept_name中選擇25個隨機條目。 例如。在表Department中有10個具有唯一ID的條目。 所以結果查詢將返回25(random) * 10 = 250行。MySql數據庫查詢從每個類別中選擇隨機數?

到目前爲止我正在研究這個查詢,但它有什麼問題。

Select * from Employee where dept in (Select id from Department) RAND; 
+0

僱主表沒有ID字段 –

+0

@Mayeulsgc對不起我的壞。我已經修復了查詢 – jpm

+0

而不是RAND嘗試命令rand()limit 10' –

回答

0

大概就像下面:

SELECT d.id, GROUP_CONCAT(name) employee_list FROM Department d JOIN (

    SELECT name FROM EMPLOYEE e WHERE d.id = e.dept ORDER BY RAND() LIMIT 25 
) v 

    GROUP BY d.id 
    LIMIT 10 
+0

@downvoter,你會介意說明 – slier

0

一種選擇是每個部門GROUP_CONCAT員工,然後使用限制的SUBSTRING_INDEX()名單25個條目。然後用員工表連接的有限值,如:

SELECT e.* FROM Employee e 
JOIN (
    SELECT SUBSTRING_INDEX(GROUP_CONCAT(eid ORDER BY RAND()), ',', 25) EmpList 
    FROM Employee 
    GROUP BY dept 
) t 
ON FIND_IN_SET(e.eid, t.EmpList) 

工作小提琴:http://sqlfiddle.com/#!9/1bd04/1

注:GROUP_CONCAT有1024默認限額,這可以增加。


第二種選擇是爲每個部門的所有員工分配行號,然後將結果限制爲每個部門25個。這一個不使用group_concat

SET @num := 0, @d_id := ''; 

SELECT eid, name, dept 
FROM (
    SELECT e.*, 
    @num := IF(@d_id = e.dept, @num + 1, 1) AS row_number, 
    @d_id := e.dept AS dummy 
    FROM (
    SELECT * FROM Employee ORDER BY dept, RAND() 
    ) e 
) t 
WHERE t.row_number <= 25 

工作小提琴:http://sqlfiddle.com/#!9/1bd04/22

注:上述兩個限制每個部門員工2用於演示目的小提琴。