要选择随机行,请使用rand()
MySQL中的LIMIT和LIMIT。语法如下:
SELECT * FROM yourTableName ORDER BY RAND() LIMIT 1;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table generateRandomRow -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Age int, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下:
mysql> insert into generateRandomRow(Name,Age) values('John',23); mysql> insert into generateRandomRow(Name,Age) values('Larry',21); mysql> insert into generateRandomRow(Name,Age) values('David',21); mysql> insert into generateRandomRow(Name,Age) values('Carol',24); mysql> insert into generateRandomRow(Name,Age) values('Bob',27); mysql> insert into generateRandomRow(Name,Age) values('Mike',29); mysql> insert into generateRandomRow(Name,Age) values('Sam',26);
使用select语句显示表中的所有记录。查询如下:
mysql> select *from generateRandomRow;
以下是输出:
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | John | 23 | | 2 | Larry | 21 | | 3 | David | 21 | | 4 | Carol | 24 | | 5 | Bob | 27 | | 6 | Mike | 29 | | 7 | Sam | 26 | +----+-------+------+ 7 rows in set (0.00 sec)
这是使用来从表中选择随机行的查询rand()
。查询如下:
mysql> select *from generateRandomRow order by rand() limit 1;
输出显示随机行:
+----+------+------+ | Id | Name | Age | +----+------+------+ | 5 | Bob | 27 | +----+------+------+ 1 row in set (0.00 sec)
现在,当我们再次运行查询时,以下随机行将可见:
mysql> select *from generateRandomRow order by rand() limit 1;
以下是输出:
+----+------+------+ | Id | Name | Age | +----+------+------+ | 6 | Mike | 29 | +----+------+------+ 1 row in set (0.00 sec)