note 26418 added to function.rand
| From: | igge at netpond dot com | Date: | Wed, 30 Oct 2002 10:35:26 +0000 |
| Subject: | note 26418 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-38742@lists.php.net to get a copy of this message | ||
About selecting random rows from a MySQL table:
SELECT * FROM tablename ORDER BY RAND() LIMIT 1
works for small tables, but once the tables grow larger than 300,000 records or so this will be very
slow because MySQL will have to process ALL the entries from the table, order them randomly and then
return the first row of the ordered result, and this sorting takes long time. Instead you can do it
like this (atleast if you have an auto_increment PK):
SELECT MIN(id), MAX(id) FROM tablename;
Fetch the result into $a
$id=rand($a[0],$a[1]);
SELECT * FROM tablename WHERE id>='$d' LIMIT 1
--
http://www.php.net/manual/en/function.rand.php
http://master.php.net/manage/user-notes.php?action=edit+26418
http://master.php.net/manage/user-notes.php?action=delete+26418
http://master.php.net/manage/user-notes.php?action=reject+26418