Skip to content

Instantly share code, notes, and snippets.

@ghalusa
Created May 8, 2013 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghalusa/5538022 to your computer and use it in GitHub Desktop.
Save ghalusa/5538022 to your computer and use it in GitHub Desktop.
Efficiently Selecting Random Rows From a MySQL Table
public function getRandomRecords()
{
// Select the first id in the target table
$statement = $this->db->prepare("SELECT some_id
FROM table_name
ORDER BY some_id ASC LIMIT 1");
$statement->execute();
$lowest_id = $statement->fetch(PDO::FETCH_ASSOC);
// Select the last id in the target table
$statement = $this->db->prepare("SELECT some_id
FROM table_name
ORDER BY some_id DESC LIMIT 1");
$statement->execute();
$highest_id = $statement->fetch(PDO::FETCH_ASSOC);
$records_array = array();
while(true)
{
// Generate a random integer
$random_id = rand( $lowest_id['some_id'], $highest_id['some_id'] );
// Check to see if the record exists
$statement = $this->db->prepare("SELECT col_one, col_two, etc...
FROM table_name
WHERE some_id = {$random_id}";
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
// If it exists, add it to the array
if($result) {
$records_array[] = $record;
}
$i++;
// If the array contains 5 records, stop
if(count($records_array) == 5) {
break;
}
}
return $records_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment