當我們在查詢中使用 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)
從上面的結果集中可以看出,每次執行查詢時,它都會傳回一組隨機不同的值或行。
以上是我們如何每次從 MySQL 表中隨機取得不同的行或值集?的詳細內容。更多資訊請關注PHP中文網其他相關文章!