显示来自 MySQL 表的随机行


要显示单个随机行,使用 RAND() 和 LIMIT。此处使用 LIMIT 获取记录数,因为我们只想要单个行,因此使用 LIMIT 1。我们先创建一个表 -

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(50),
   Quote text
);
Query OK, 0 rows affected (0.71 sec)

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

mysql> insert into DemoTable(Name,Quote) values('Chris','MySQL is a relational database');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name,Quote) values('Robert','Java is an Object Oriented Programming Language');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name,Quote) values('Mike','C is a Procedural Language');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Quote) values('David','Hibernate and spring is a framework');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

这将生成以下输出 -

+----+--------+-------------------------------------------------+
| Id | Name   | Quote                                           |
+----+--------+-------------------------------------------------+
|  1 | Chris  | MySQL is a relational database                  |
|  2 | Robert | Java is an Object Oriented Programming Language |
|  3 | Mike   | C is a Procedural Language                      |
|  4 | David  | Hibernate and spring is a framework             |
+----+--------+-------------------------------------------------+
4 rows in set (0.00 sec)

以下是显示 MySQL 表中随机行的查询 -

mysql> select Id,Name,Quote from DemoTable order by rand() limit 1;

这将生成以下输出 -

+----+------+----------------------------+
| Id | Name | Quote                      |
+----+------+----------------------------+
|  3 | Mike | C is a Procedural Language |
+----+------+----------------------------+
1 row in set (0.00 sec)

更新于: 03-Oct-2019

195 浏览量

开启您的 职业

通过完成课程获得认证

开始吧
广告