从 MySQL 表中选择固定数量的随机记录?
对于随机记录,你可以使用 rand() 方法。若要设置记录的数量,请使用 LIMIT -
select *from yourTableName order by rand() limit numberOfRecords;
让我们先创建一个表 -
mysql> create table DemoTable -> ( -> LastName varchar(100) -> ); Query OK, 0 rows affected (0.51 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable values('Brown'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('Smith'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Taylor'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Miller'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Johnson'); Query OK, 1 row affected (0.20 sec)
使用 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)
广告