MySql数据库查询从每个类别中选择随机?

时间:2017-03-07 06:52:40

标签: mysql database

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行。

到目前为止,我正在研究这个问题,但是它出了问题。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

一个选项是每个部门的GROUP_CONCAT名员工,然后使用SUBSTRING_INDEX()将列表限制为25个条目。然后将有限值与employee表一起加入,如下所示:

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名员工用于演示目的。