使用RAND()和LIMIT子句在MySQL数据库中选择两个随机行-
select *from yourTableName order by rand() limit 2;
让我们首先创建一个表-
mysql>create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientFirstName varchar(20) );
使用插入命令在表中插入一些记录-
mysql>insert into DemoTable(ClientFirstName) values('Robert'); mysql>insert into DemoTable(ClientFirstName) values('Chris'); mysql>insert into DemoTable(ClientFirstName) values('Jace'); mysql>insert into DemoTable(ClientFirstName) values('James'); mysql>insert into DemoTable(ClientFirstName) values('David'); mysql>insert into DemoTable(ClientFirstName) values('John'); mysql>insert into DemoTable(ClientFirstName) values('Mike');
以下是使用select语句显示表中所有记录的查询-
mysql>select *from DemoTable;
这将产生以下输出-
+----+-----------------+ | Id | ClientFirstName | +----+-----------------+ | 1 | Robert | | 2 | Chris | | 3 | Jace | | 4 | James | | 5 | David | | 6 | John | | 7 | Mike | +----+-----------------+ 7 rows in set (0.00 sec)
以下是在MySQL数据库中选择两个随机行的查询。
mysql>select *from DemoTable order by rand() limit 2;
这将产生以下输出-
+----+-----------------+ | Id | ClientFirstName | +----+-----------------+ | 4 | James | | 2 | Chris | +----+-----------------+ 2 rows in set (0.00 sec)