如何在MySQL中随机排序查询结果并选择随机行?

要随机排序查询结果,请使用ORDER BY RAND()。语法如下-

select * from DemoTable1559 where yourColumnName IN(yourValue1,yourValue2,....N) order by rand() limit yourLimitValue;

让我们首先创建一个表-

mysql> create table DemoTable1559
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(20),
   -> EmployeeAge int
   -> );

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1559 values(101,'Bob',28);
mysql> insert into DemoTable1559 values(102,'Robert',26);
mysql> insert into DemoTable1559 values(103,'Sam',25);
mysql> insert into DemoTable1559 values(104,'Mike',29);
mysql> insert into DemoTable1559 values(105,'John',34);
mysql> insert into DemoTable1559 values(106,'Carol',31);

使用select语句显示表中的所有记录-

mysql> select * from DemoTable1559;

这将产生以下输出-

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|        101 | Bob          |          28 |
|        102 | Robert       |          26 |
|        103 | Sam          |          25 |
|        104 | Mike         |          29 |
|        105 | John         |          34 |
|        106 | Carol        |          31 |
+------------+--------------+-------------+
6 rows in set (0.00 sec)

以下是查询以对查询结果进行随机排序并选择随机行-

mysql> select * from DemoTable1559 where EmployeeId IN(101,103,106) order by rand() limit 3;

这将产生以下输出-

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|        101 | Bob          |          28 |
|        103 | Sam          |          25 |
|        106 | Carol        |          31 |
+------------+--------------+-------------+
3 rows in set (0.00 sec)