选择 MySQL 表中存在的随机行?

mysqlmysqli database更新于 2025/10/4 14:04:17

要选择随机值,请使用 rand()。这里,我们只选择一个随机值,因此使用 LIMIT 1。以下是语法 −

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

首先我们创建一个表 −

mysql> create table DemoTable735 (Amount int);
Query OK, 0 rows affected (0.57 sec)

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

mysql> insert into DemoTable735 values(984474734);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable735 values(489393323);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable735 values(23432333);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable735 values(8949933);
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable735;

这将产生以下输出 -

+-----------+
| Amount    |
+-----------+
| 984474734 |
| 489393323 |
| 23432333  |
| 8949933   |
+-----------+
4 rows in set (0.00 sec)

以下是在 MySQL 中选择随机行的查询

mysql> select *from DemoTable735 order by rand() limit 1;

这将产生以下输出 -

+-----------+
| Amount    |
+-----------+
| 489393323 |
+-----------+
1 row in set (0.00 sec)

相关文章


有用资源