如何从MySQL数据库中选择随机记录?
为此,您可以使用ORDER BY RAND LIMIT。让我们首先创建一个表-
mysql> create table DemoTable1581-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName varchar(20)
-> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1581(StudentName) values('Chris');mysql> insert into DemoTable1581(StudentName) values('Bob');
mysql> insert into DemoTable1581(StudentName) values('Sam');
mysql> insert into DemoTable1581(StudentName) values('Mike');
mysql> insert into DemoTable1581(StudentName) values('Carol');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1581;
这将产生以下输出-
+-----------+-------------+| StudentId | StudentName |
+-----------+-------------+
| 1 | Chris |
| 2 | Bob |
| 3 | Sam |
| 4 | Mike |
| 5 | Carol |
+-----------+-------------+
5 rows in set (0.00 sec)
这是从MySQL数据库中选择随机记录的查询-
mysql> select * from DemoTable1581 order by rand() limit 1;
这将产生以下输出-
+-----------+-------------+| StudentId | StudentName |
+-----------+-------------+
| 4 | Mike |
+-----------+-------------+
1 row in set (0.07 sec)
以上是 如何从MySQL数据库中选择随机记录? 的全部内容, 来源链接: utcz.com/z/359456.html