如何在MySQL中检索随机行或多个随机行?
您可以RAND()
为此使用方法。要检索随机行,请使用以下语法
SELECT *FROM yourTableName ORDER BY RAND() LIMIT yourIntegerNumber;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table gettingRandomRow-> (
-> CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> CustomerName varchar(100)
-> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into gettingRandomRow(CustomerName) values('Chris');mysql> insert into gettingRandomRow(CustomerName) values('Robert');
mysql> insert into gettingRandomRow(CustomerName) values('Ramit');
mysql> insert into gettingRandomRow(CustomerName) values('James');
mysql> insert into gettingRandomRow(CustomerName) values('Jace');
mysql> insert into gettingRandomRow(CustomerName) values('Mike');
mysql> insert into gettingRandomRow(CustomerName) values('Sam');
mysql> insert into gettingRandomRow(CustomerName) values('Bob');
mysql> insert into gettingRandomRow(CustomerName) values('Carol');
mysql> insert into gettingRandomRow(CustomerName) values('David');
mysql> insert into gettingRandomRow(CustomerName) values('Maxwell');
mysql> insert into gettingRandomRow(CustomerName) values('Larry');
mysql> insert into gettingRandomRow(CustomerName) values('John');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from gettingRandomRow;
以下是输出
+------------+--------------+| CustomerId | CustomerName |
+------------+--------------+
| 1 | Chris |
| 2 | Robert |
| 3 | Ramit |
| 4 | James |
| 5 | Jace |
| 6 | Mike |
| 7 | Sam |
| 8 | Bob |
| 9 | Carol |
| 10 | David |
| 11 | Maxwell |
| 12 | Larry |
| 13 | John |
+------------+--------------+
13 rows in set (0.00 sec)
这是获取一个随机行或多个随机行的查询。
情况1:查询如下-
mysql> select *from gettingRandomRow order by rand() LIMIT 1;
以下是输出
+------------+--------------+| CustomerId | CustomerName |
+------------+--------------+
| 13 | John |
+------------+--------------+
1 row in set (0.00 sec)
情况2:查询如下-
mysql> select *from gettingRandomRow order by rand() LIMIT 2;
以下是输出
+------------+--------------+| CustomerId | CustomerName |
+------------+--------------+
| 2 | Robert |
| 3 | Ramit |
+------------+--------------+
2 rows in set (0.00 sec)
情况3:查询如下-
mysql> select *from gettingRandomRow order by rand() LIMIT 2;
以下是输出
+------------+--------------+| CustomerId | CustomerName |
+------------+--------------+
| 4 | James |
| 9 | Carol |
+------------+--------------+
2 rows in set (0.00 sec)
以上是 如何在MySQL中检索随机行或多个随机行? 的全部内容, 来源链接: utcz.com/z/347223.html