在MySQL中,如何将结果集中的行或值的集合随机化?
借助RAND()
与ORDERBY子句一起使用的函数,可以在结果集中将行或值的集合随机化。为了理解它认为表'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)
现在,下面的查询将使用ORDERBTRAND()
来随机整理结果集中的行集-
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)