在MySql中获取随机记录

时间:2016-08-12 06:31:14

标签: mysql sql

我有一个sql表,Employee有4列。

  • 编号
  • 名称
  • 地址
  • 状态 - 固定类型(枚举)。拥有3个固定值 - OPENCLOSEDPENDING

我们假设表中的总记录为200。

现在,我想形成一个返回的查询 -

  • 50条状态为“OPEN”的随机记录。
  • 25条状态为“已关闭”的随机记录。
  • 45条随机记录,状态为“PENDING”。

我尝试过一个支离破碎的查询,它运行正常,但为整个场景寻找单一查询解决方案。

Select * from Employee a where a.Status = 'OPEN' ORDER BY RAND() LIMIT 50
Select * from Employee a where a.Status = 'CLOSED' ORDER BY RAND() LIMIT 25
Select * from Employee a where a.Status = 'PENDING' ORDER BY RAND() LIMIT 45

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:4)

您是需要将其作为单个查询(轻度痛苦)还是3个单独的查询?

作为3个单独的查询,最简单的选项就像

Select * from Employee where Status = 'OPEN' ORDER BY RAND() LIMIT 50;
Select * from Employee where Status = 'CLOSED' ORDER BY RAND() LIMIT 25;
Select * from Employee where Status = 'PENDING' ORDER BY RAND() LIMIT 45;

答案 1 :(得分:3)

使用Union组合多个查询,并记住为每个子/父查询分配别名。

select * from ((Select * from Employee a where a.Status = 'OPEN' ORDER BY RAND() LIMIT 50) 
union 
(Select * from Employee b where b.Status = 'CLOSED' ORDER BY RAND() LIMIT 25) 
union 
(Select * from Employee c where c.Status = 'PENDING' ORDER BY RAND() LIMIT 45)) d;

我希望这对某人有用。