要随机选择行,请使用ORDER BYRAND()
和LIMIT。将DISTINCT用于不同的行。我们首先来看一个示例并创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(40) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Name) values('John Doe'); mysql> insert into DemoTable(Name) values('Chris Brown'); mysql> insert into DemoTable(Name) values('Adam Smith'); mysql> insert into DemoTable(Name) values('John Doe'); mysql> insert into DemoTable(Name) values('John Doe'); mysql> insert into DemoTable(Name) values('Chris Brown'); mysql> insert into DemoTable(Name) values('Adam Smith');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-------------+ | Id | Name | +----+-------------+ | 1 | John Doe | | 2 | Chris Brown | | 3 | Adam Smith | | 4 | John Doe | | 5 | John Doe | | 6 | Chris Brown | | 7 | Adam Smith | +----+-------------+ 7 rows in set (0.00 sec)
以下是查询以随机选择表中的两个不同行-
mysql> select distinct Name from DemoTable order by rand() limit 3;
这将产生以下输出-
+-------------+ | Name | +-------------+ | Chris Brown | | John Doe | | Adam Smith | +-------------+ 3 rows in set (0.00 sec)