如何在 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
   -> );
Query OK, 0 rows affected (1.22 sec)

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

mysql> insert into DemoTable1559 values(101,'Bob',28);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1559 values(102,'Robert',26);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1559 values(103,'Sam',25);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1559 values(104,'Mike',29);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1559 values(105,'John',34);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1559 values(106,'Carol',31);
Query OK, 1 row affected (0.19 sec)

使用 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)

更新于: 12-12-2019

389 次浏览

开启您的 生涯

完成课程即可获得认证

开始
广告