從 MySQL 中選擇隨機結果?


你需要使用 rand() 函式從 MySQL 中選擇隨機結果。

語法如下:

select *from yourTableName order by rand() limit 1;

為了理解上述語法,讓我們建立一個表格。建立表格的查詢如下:

mysql> create table selectRandomRecord
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.53 sec)

使用 insert 命令在表格中插入一些記錄。

查詢如下:

mysql> insert into selectRandomRecord(StudentName) values('John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into selectRandomRecord(StudentName) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectRandomRecord(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into selectRandomRecord(StudentName) values('Sam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectRandomRecord(StudentName) values('Mike');
Query OK, 1 row affected (0.16 sec)
mysql> insert into selectRandomRecord(StudentName) values('Robert');
Query OK, 1 row affected (0.20 sec)

使用 select 語句從表格中顯示所有記錄。

查詢如下:

mysql> select *from selectRandomRecord;

輸出如下:

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | John        |
| 2         | Carol       |
| 3         | Bob         |
| 4         | Sam         |
| 5         | Mike        |
| 6         | Robert      |
+-----------+-------------+
6 rows in set (0.00 sec)

以下是從 MySQL 中選擇隨機結果的查詢。

mysql> select *from selectRandomRecord order by rand() limit 1;

輸出如下:

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 3         | Bob         |
+-----------+-------------+
1 row in set (0.00 sec)

現在再次執行相同的查詢以獲得另一個隨機值

mysql> select *from selectRandomRecord order by rand() limit 1;

輸出如下:

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 5         | Mike        |
+-----------+-------------+
1 row in set (0.00 sec)

更新於:30-7-2019

107 次檢視

開啟你的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.