Re: How to optimize select of random record in DB ?
| From: | Matthew Weier O'Phinney | Date: | Fri, 15 Oct 2004 06:34:17 +0000 |
| Subject: | Re: How to optimize select of random record in DB ? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-199561@lists.php.net to get a copy of this message | ||
* -{ Rene Brehmer }- <metalbunny@metalbunny.net>:
> I made this code to pick a random record from a changeable number of
> records in a given table.
> I'm just curious if any of the more awake coders out there can see a way to
> optimize this for better performance, since there's several other DB
> queries on the same page.
>
> $records = mysql_query("SELECT COUNT(*) AS count FROM persons") or
> die('Unable to get record count<br>'.mysql_error());
> $totalcount = mysql_result($records,0) - 1;
> $rndrecord = rand(0,$totalcount);
> $personquery = mysql_query("SELECT personID FROM persons LIMIT
> $rndrecord,1") or die('Unable to get random record<br>'.mysql_error());
> $personID = mysql_result($personquery,0);
Since you're using mysql, why not use the RAND() function?
$sql = "SELECT personID FROM persons ORDER BY RAND() LIMIT 1";
$query = mysql_query($sql) or die("Unable to get random record");
$personID = mysql_result($query, 0);
I've used this quite a bit -- much easier than using PHP to do it.
--
Matthew Weier O'Phinney | mailto:matthew@garden.org
Webmaster and IT Specialist | http://www.garden.org
National Gardening Association | http://www.kidsgardening.com
802-863-5251 x156 | http://nationalgardenmonth.org