Quick Search:
CODE
Oracle PL/SQL Code Library
JOBS
Find Or Post Oracle Jobs
FORUM
Oracle Discussion & Chat
 mySQL: Fast random row picker #2 Jump to:  
Category: >> mySQL >> Fast random row picker #2 Bookmark and Share

<< lastnext >>

Snippet Name: Fast random row picker #2

Description: This will return a random row in about 0.05 seconds, regardless of the size of the table. If the max_id of the table is not dynamically changing, the function can be rewritten to only execute one database query instead of two.

Comment: (none)

Language: MYSQL
Highlight Mode: MYSQL
Last Modified: February 28th, 2009

FUNCTION random_row($table, $column) {
 
  $max_sql = "SELECT max(" . $column . ") 
 
              AS max_id
 
              FROM " . $table;
 
  $max_row = mysql_fetch_array(mysql_query($max_sql));
 
  $random_number = mt_rand(1, $max_row['max_id']);
 
  $random_sql = "SELECT * FROM " . $table . "
 
                 WHERE " . $column . " >= " . $random_number . " 
 
                 ORDER BY " . $column . " ASC
 
                 LIMIT 1";
 
  $random_row = mysql_fetch_row(mysql_query($random_sql));
 
  IF (!is_array($random_row)) {
 
      $random_sql = "SELECT * FROM " . $table . "
 
                     WHERE " . $column . " < " . $random_number . " 
 
                     ORDER BY " . $column . " DESC
 
                     LIMIT 1";
 
      $random_row = mysql_fetch_row(mysql_query($random_sql));
 
  }
 
  return $random_row;
}


Free
Oracle Magazine
Subscriptions
and Oracle White Papers


SQL University.net courses meet the most demanding needs of the business world for advanced education in a cost-effective manner. SQL University.net courses are available immediately for IT professionals and can be taken without disruption of your workplace schedule or processes.

Compared to traditional travel-based training, SQL University.net saves time and valuable corporate resources, allowing companies to do more with less. That's our mission, and that's what we deliver.

Click here to find out more
 
Home      :      Code Library      :      Sponsors      :      Privacy      :      Terms of Use      :      Contact Us 241 users online    © 2009 psoug.org

PSOUG LOGIN
Username: 
Password: 
Forgot your password?