MySQL 如何使用RAND()函数来随机排列 MySQL 表格中的行?
当我们在 MySQL 中使用带有 RAND() 函数的 ORDER BY 子句时,结果集会随机洗牌排列。换句话说,结果集会随机排列。为了理解这一点,我们考虑一个名为“Employee”的表格,包含以下记录 —
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)
现在,以下查询将使用 ORDER BY RAND() 来随机排列结果集中的行 —
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)
阅读更多:MySQL 教程