如何随机选择 MySQL 表中不同的行?
要随机选择行,请将 ORDER BY RAND() 与 LIMIT 结合使用。针对不同的行,使用 DISTINCT。我们首先看一个示例并创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(40) ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(Name) values('John Doe'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Name) values('Chris Brown'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Name) values('Adam Smith'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(Name) values('John Doe'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable(Name) values('John Doe'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(Name) values('Chris Brown'); Query OK, 1 row affected (0.53 sec) mysql> insert into DemoTable(Name) values('Adam Smith'); Query OK, 1 row affected (0.12 sec)
使用 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)
广告