从MySQL表中选择固定数量的随机记录?

对于随机记录,可以使用rand()方法。要设置记录数,请使用LIMIT-

select *from yourTableName order by rand() limit numberOfRecords;

让我们首先创建一个表-

mysql> create table DemoTable
   -> (
   -> LastName varchar(100)
   -> );

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

mysql> insert into DemoTable values('Brown');

mysql> insert into DemoTable values('Smith');

mysql> insert into DemoTable values('Taylor');

mysql> insert into DemoTable values('Miller');

mysql> insert into DemoTable values('Johnson');

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

mysql> select *from DemoTable;

输出结果

这将产生以下输出-

+----------+
| LastName |
+----------+
| Brown    |
| Smith    |
| Taylor   |
| Miller   |
| Johnson  |
+----------+
5 rows in set (0.00 sec)

以下是选择固定数量的随机记录的查询-

mysql> select *from DemoTable order by rand() limit 4;

输出结果

这将产生以下输出-

+----------+
| LastName |
+----------+
| Brown    |
| Miller   |
| Johnson  |
| Taylor   |
+----------+
4 rows in set (0.03 sec)