Home > Database > Mysql Tutorial > body text

How can we randomly get a different set of rows or values ​​from a MySQL table each time?

PHPz
Release: 2023-08-28 23:29:09
forward
936 people have browsed it

我们如何每次从 MySQL 表中随机获取不同的行或值集?

When we use the RAND() function with the ORDER BY and LIMIT clauses in a query, MySQL returns a different set of rows or values ​​every time. To understand it, consider a table "Employee" with the following records -

mysql> Select * from Employee;
+----+--------+--------+
| ID | Name   | Salary |
+----+--------+--------+
| 1  | Gaurav | 50000  |
| 2  | Rahul  | 20000  |
| 3  | Advik  | 25000  |
| 4  | Aarav  | 65000  |
| 5  | Ram    | 20000  |
| 6  | Mohan  | 30000  |
| 7  | Aryan  | NULL   |
| 8  | Vinay  | NULL   |
+----+--------+--------+
8 rows in set (0.00 sec)
Copy after login

Now, the following query will use RAND() function and use both ORDER BY and LIMIT clauses in the query to return random Different set of values ​​or rows -

mysql> Select * from employee ORDER BY RAND() LIMIT 4;
+----+-------+--------+
| ID | Name  | Salary |
+----+-------+--------+
| 5  | Ram   | 20000  |
| 4  | Aarav | 65000  |
| 6  | Mohan | 30000  |
| 8  | Vinay | NULL   |
+----+-------+--------+
4 rows in set (0.00 sec)

mysql> Select * from employee ORDER BY RAND() LIMIT 4;
+----+--------+--------+
| ID | Name   | Salary |
+----+--------+--------+
| 6  | Mohan  | 30000  |
| 8  | Vinay  | NULL   |
| 2  | Rahul  | 20000  |
| 1  | Gaurav | 50000  |
+----+--------+--------+
4 rows in set (0.03 sec)

mysql> Select * from employee ORDER BY RAND() LIMIT 4;
+----+-------+--------+
| ID | Name  | Salary |
+----+-------+--------+
| 3  | Advik | 25000  |
| 8  | Vinay | NULL   |
| 7  | Aryan | NULL   |
| 5  | Ram   | 20000  |
+----+-------+--------+
4 rows in set (0.00 sec)
Copy after login

As you can see from the above result set, every time you run the query, it returns a randomly different set of values ​​or rows.

The above is the detailed content of How can we randomly get a different set of rows or values ​​from a MySQL table each time?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!