使用 MySQL 提取表中的随机行


为此,可以使用 PREPARE 语句。首先创建表 -

mysql> create table DemoTable(
   FirstName varchar(100),
   CountryName varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

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

mysql> insert into DemoTable values('Adam','US');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Chris','AUS');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Robert','UK');
Query OK, 1 row affected (0.32 sec)

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

mysql> select *from DemoTable;

这会产生以下输出 -

+-----------+-------------+
| FirstName | CountryName |
+-----------+-------------+
| Adam      | US          |
| Chris     | AUS         |
| Robert    | UK          | 
+-----------+-------------+
3 rows in set (0.00 sec)

以下是通过单个查询提取随机行的查询 -

mysql> set @value := ROUND((select count(*) from DemoTable) * rand());
Query OK, 0 rows affected (0.00 sec)
mysql> set @query := CONCAT('select *from DemoTable LIMIT ', @value , ', 1');
Query OK, 0 rows affected (0.00 sec)
mysql> prepare myStatement from @query ;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute myStatement;
+-----------+-------------+
| FirstName | CountryName |
+-----------+-------------+
| Chris     | AUS         |
+-----------+-------------+
1 row in set (0.00 sec)
mysql> deallocate prepare myStatement;
Query OK, 0 rows affected (0.00 sec)

更新于: 2019-09-27

117 次浏览

启动您的 职业

完成课程认证

开始
广告