Selecting Random Rows with MySQL: A Detailed Solution
The question arises frequently about how to effectively select random rows from a large MySQL table without resorting to the ORDER BY RAND() method, which is known to be inefficient for larger datasets. To address this challenge, let's explore a viable solution:
MySQL-Based Approach:
Utilize the combination of the following SQL statements:
SET @r := (SELECT FLOOR(RAND() * (SELECT COUNT(*) FROM mytable))); SET @sql := CONCAT('SELECT * FROM mytable LIMIT 1 OFFSET ', @r); PREPARE stmt1 FROM @sql; EXECUTE stmt1;
This approach involves:
PHP-Based Approach:
If you prefer to work with PHP, you can employ the following code snippet:
<?php $mysqli->begin_transaction(); $result = $mysqli->query("SELECT COUNT(*) FROM mytable"); $row = $result->fetch_row(); $count = $row[0]; $offset = mt_rand(0, $count); $result = $mysqli->query("SELECT * FROM mytable LIMIT 1 OFFSET $offset"); ... $mysqli->commit();
This approach entails:
The above is the detailed content of How to Efficiently Select Random Rows from a Large MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!