View Full Version : Random Query
Socraties
04-09-2004, 05:57 PM
I have been tasked with getting daily quotes out of a sql database, there needs to be 3 that are randomly selected. I have not found any documentation in regards to doing this.
How would I qurey a database and pull 3 quotes of the day out randomly. This should even occur when a user refreshes the page, is there a sql function that would do this? or do I need to do it via php, perl, etc...
zigo86
04-09-2004, 09:59 PM
$result = mysql_query("select * from table order by rand() limit 3");
I have not found any documentation in regards to doing this.
you probably did not search the manual or this forum or the php forum for "random" or you'd found
SELECT ... FROM tabl ORDER BY RAND() LIMIT 3
from http://dev.mysql.com/doc/mysql/en/Mathematical_functions.html
You can't use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times. As of MySQL 3.23, you can retrieve rows in random order like this:
mysql> SELECT * FROM tbl_name ORDER BY RAND();
ORDER BY RAND() combined with LIMIT is useful for selecting a random sample of a set of rows::
mysql> SELECT * FROM table1, table2 WHERE a=b AND c<d
-> ORDER BY RAND() LIMIT 1000;
Note that RAND() in a WHERE clause is re-evaluated every time the WHERE is executed. RAND() is not meant to be a perfect random generator, but instead a fast way to generate ad hoc random numbers that will be portable between platforms for the same MySQL version.
vBulletin® v3.8.2, Copyright ©2000-2009, Jelsoft Enterprises Ltd.