从MySQL中选择随机结果?
您需要使用rand()函数从MySQL中选择随机结果。
语法如下
select *from yourTableName order by rand() limit 1;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table selectRandomRecord -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20) -> );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into selectRandomRecord(StudentName) values('John');
mysql> insert into selectRandomRecord(StudentName) values('Carol');
mysql> insert into selectRandomRecord(StudentName) values('Bob');
mysql> insert into selectRandomRecord(StudentName) values('Sam');
mysql> insert into selectRandomRecord(StudentName) values('Mike');
mysql> insert into selectRandomRecord(StudentName) values('Robert');使用select语句显示表中的所有记录。
查询如下
mysql> select *from selectRandomRecord;
以下是输出
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Sam | | 5 | Mike | | 6 | Robert | +-----------+-------------+ 6 rows in set (0.00 sec)
以下是从MySQL中选择随机结果的查询。
mysql> select *from selectRandomRecord order by rand() limit 1;
以下是输出
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 3 | Bob | +-----------+-------------+ 1 row in set (0.00 sec)
现在再次执行相同的查询以获取另一个随机值
mysql> select *from selectRandomRecord order by rand() limit 1;
以下是输出
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 5 | Mike | +-----------+-------------+ 1 row in set (0.00 sec)
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短