note 104156 added to function.rand
| From: | HamzaKubba at osu1 dot php dot net | Date: | Fri, 27 May 2011 01:47:21 +0000 |
| Subject: | note 104156 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-180068@lists.php.net to get a copy of this message | ||
Regarding getting a random row from a table in MySQL (or Postgres), it is better to offload that to
the database rather than doing one query to grab tons of data from the database, then a second query
to fetch one row.
I.e., this is far more efficient for small to medium sized tables (i.e. less than 1 mil. rows):
SELECT * FROM [TABLE] ORDER BY RAND() LIMIT 1;
For large tables, this is both easy to implement and efficient:
SELECT COUNT(id) AS number_of_rows FROM [TABLE];
then something alone the lines of:
<?php
$sql = "SELECT * FROM [TABLE] LIMIT 1 OFFSET ".(rand(0, $number_of_rows - 1));
// ...
?>
----
Server IP: 69.147.83.197
Probable Submitter: 72.10.153.136
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/104156
Del: integrated -- https://master.php.net/note/delete/104156/integrated
Del: useless -- https://master.php.net/note/delete/104156/useless
Del: bad code -- https://master.php.net/note/delete/104156/bad+code
Del: spam -- https://master.php.net/note/delete/104156/spam
Del: non-english -- https://master.php.net/note/delete/104156/non-english
Del: in docs -- https://master.php.net/note/delete/104156/in+docs
Del: other reasons-- https://master.php.net/note/delete/104156
Reject -- https://master.php.net/note/reject/104156
Search -- https://master.php.net/manage/user-notes.php