使用RAND()
随机的,而LIMIT 3的值的数量,即在这里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) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable646(FirstName) values('John'); mysql> insert into DemoTable646(FirstName) values('Bob'); mysql> insert into DemoTable646(FirstName) values('Chris'); mysql> insert into DemoTable646(FirstName) values('David'); mysql> insert into DemoTable646(FirstName) values('Bob'); mysql> insert into DemoTable646(FirstName) values('Carol'); mysql> insert into DemoTable646(FirstName) values('Mike');
使用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)