如何在 MySQL 表中显示 3 个随机值?


对于随机,使用 RAND();而对于数值,例如此处为 3,使用 LIMIT 3 −

select yourColumnName from yourTableName order by rand() limit 3;

首先让我们创建一个表 −

mysql> create table DemoTable646 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,FirstName varchar(100)
);
Query OK, 0 rows affected (0.76 sec)

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

mysql> insert into DemoTable646(FirstName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable646(FirstName) values('Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable646(FirstName) values('Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable646(FirstName) values('David');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable646(FirstName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable646(FirstName) values('Carol');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable646(FirstName) values('Mike');
Query OK, 1 row affected (0.10 sec)

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

mysql> select *from DemoTable646;

这将产生以下输出 −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | John      |
|  2 | Bob       |
|  3 | Chris     |
|  4 | David     |
|  5 | Bob       |
|  6 | Carol     |
|  7 | Mike      |
+----+-----------+
7 rows in set (0.00 sec)

以下是可以从 MySQL 表中显示 3 个随机值:−

mysql> select FirstName from DemoTable646 order by rand() limit 3;

这将产生以下输出 −

+-----------+
| FirstName |
+-----------+
| Mike      |
| John      |
| Chris     |
+-----------+
3 rows in set (0.00 sec)

更新日期:2019 年 8 月 23 日

119 次浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告