Select*fromemployee;+----+--------+--------+|ID|Name |Salary|+----+--------+--------+|1 |Gaurav|50000 ||2 |Rahul"/> Select*fromemployee;+----+--------+--------+|ID|Name |Salary|+----+--------+--------+|1 |Gaurav|50000 ||2 |Rahul">

Home  >  Article  >  Database  >  How to shuffle a MySQL rowset using the RAND() function in an ORDER BY clause?

How to shuffle a MySQL rowset using the RAND() function in an ORDER BY clause?

WBOY
WBOYforward
2023-08-23 20:09:061572browse

如何在 ORDER BY 子句中使用 RAND() 函数来打乱 MySQL 行集?

When we use the MySQL ORDER BY clause with the RAND() function, the result set will have a shuffled set of rows. In other words, the result set will be in random order. 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)

Now, the following query will use ORDER BT RAND() to shuffle the set of rows in the result set -

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

The above is the detailed content of How to shuffle a MySQL rowset using the RAND() function in an ORDER BY clause?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete