note 82807 added to function.rand

From: Date: Sat, 26 Apr 2008 19:27:25 +0000
Subject: note 82807 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-138830@lists.php.net to get a copy of this message
emad_ramahi at hotmail dot com: I've actually noticed that with a large dataset (100k rows), the query dramatically slows down the server and performance is way too bad. The way I see it, you have to workable solutions: Using PHP: <?php //$Table holds the name of the table we're getting the random row from //$Rows specifies how many rows we need to fetch function mysql_rand ($Query, $Rows = 1) { //getting the table name from $query //what you can do, is replace the $query argument with $table, //this way to dont have to search for the table's name $SQL = sprintf ('SELECT COUNT(*) FROM %s', substr ($query, stripos ($query, 'from')+5, strpos ($query, ' '))); $Max = mysql_result (mysql_query ($SQL), 0); $Random = rand (0, $Max); //If the random number is 99, and the database only has 100 rows //We'll subtract the random number, so we don't exceed 100, thus preventing a MySQL error message return $Query . sprintf ('LIMIT %d, %d', ($Max < $Rows) ? 0 : (($Random > $Max - $Rows) ? $Max - $Rows : $Random), $Rows); } //Instead of using MySQL's RAND(), we use LIMIT to fetch rows //E.g. LIMIT 5,9 fetches from row 5, and the subsequent 9 $SQL = mysql_rand ('SELECT row FROM table'); //SELECT row FROM table LIMIT x, y ?> or SQL: SELECT * FROM Table T JOIN (SELECT FLOOR(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1; ---- Server IP: 62.73.196.231 Probable Submitter: 85.164.224.129 ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- https://master.php.net/note/edit/82807 Del: integrated -- https://master.php.net/note/delete/82807/integrated Del: useless -- https://master.php.net/note/delete/82807/useless Del: bad code -- https://master.php.net/note/delete/82807/bad+code Del: spam -- https://master.php.net/note/delete/82807/spam Del: non-english -- https://master.php.net/note/delete/82807/non-english Del: in docs -- https://master.php.net/note/delete/82807/in+docs Del: other reasons-- https://master.php.net/note/delete/82807 Reject -- https://master.php.net/note/reject/82807 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#138830) next »