Can someone please clarify how to apply the following note about avoiding LIMIT from page 16 of Peter's presentation MySQL Queries Optimization?
I have a situation where I need to select a random question from a filtered list. I found the performance of ORDER BY RAND() to be terrible. Currently, I am (A) counting the number of results, (B) using PHP to select a random number of results to skip, (C) skipping through the result set [via LIMIT] to find the corresponding Primary Key value, and then (D) pulling the single row.
Is there a faster way to do this using BETWEEN?
PHP:
// Count the number of available questions in the topic$CountQsql = "SELECT QuestionIDFROM questionsWHERE topic = 1132AND Published = 1";$CountQresult = mysql_query($CountQsql, $conn);$CountQnum = mysql_row_num($CountQresult);// Select a random number of rows to skip$SkipRows = rand(0,($CountQnum - 1));// Select the ID of the random question chosen$SelectRandQsql = "SELECT QuestionID AS QChosenFROM questionsWHERE topic = 1132AND Published = 1LIMIT {$SkipRows} , 1";$SelectRandQresult = mysql_query($SelectRandQsql, $conn)$SelectRandQarray = mysql_fetch_array($SelectRandQresult)$QChosen = $SelectRandQarray['QChosen'];// Pull Question Info$sql = "SELECT QText, Answ1, Answ2, Answ3, Answ4FROM questionsWHERE QuestionID = {$QChosen}";
| Quote: |
If you can precompute positions do it – WHERE POS BETWEEN 1001 and 1010 works much better than LIMIT 1000,10 |
I have a situation where I need to select a random question from a filtered list. I found the performance of ORDER BY RAND() to be terrible. Currently, I am (A) counting the number of results, (B) using PHP to select a random number of results to skip, (C) skipping through the result set [via LIMIT] to find the corresponding Primary Key value, and then (D) pulling the single row.
Is there a faster way to do this using BETWEEN?
PHP:
// Count the number of available questions in the topic$CountQsql = "SELECT QuestionIDFROM questionsWHERE topic = 1132AND Published = 1";$CountQresult = mysql_query($CountQsql, $conn);$CountQnum = mysql_row_num($CountQresult);// Select a random number of rows to skip$SkipRows = rand(0,($CountQnum - 1));// Select the ID of the random question chosen$SelectRandQsql = "SELECT QuestionID AS QChosenFROM questionsWHERE topic = 1132AND Published = 1LIMIT {$SkipRows} , 1";$SelectRandQresult = mysql_query($SelectRandQsql, $conn)$SelectRandQarray = mysql_fetch_array($SelectRandQresult)$QChosen = $SelectRandQarray['QChosen'];// Pull Question Info$sql = "SELECT QText, Answ1, Answ2, Answ3, Answ4FROM questionsWHERE QuestionID = {$QChosen}";
Comment