显示 MySQL 表中的随机行

mysqlmysqli database

要显示单个随机行,请使用带 LIMIT 的 RAND()。此处,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)

相关文章