如何从 MySQL 表中每次随机获取不同的一组行或值?
当我们在查询中同时使用 RAND() 函数和 ORDER BY 和 LIMIT 子句时,MySQL 每次都会返回不同的行或值集。为了了解它,请考虑一个表“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)
现在,下面的查询将在查询中同时使用 RAND() 函数和 ORDER BY 和 LIMIT 子句,随机返回不同的值集或行 -
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)
从上面的结果集中可以观察到,每次运行查询时,它都会返回随机不同的值集或行。
广告