Created
May 8, 2013 03:43
-
-
Save ghalusa/5538022 to your computer and use it in GitHub Desktop.
Efficiently Selecting Random Rows From a MySQL Table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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