Re: Re: Random Numbers..

From: Date: Tue, 09 Dec 2003 05:25:11 +0000
Subject: Re: Re: Random Numbers..
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-172226@lists.php.net to get a copy of this message
* Thus wrote Burrito Warrior (burrito-warrior@thisiswaytoocool.com): > > This would: > /* selecting a random record, where n = 1. Works fine on small tables */ > mysql> SELECT value FROM table ORDER BY RAND() LIMIT n; > > /* selecting a random record. This is good on large tables if numbering > sequence is used */ > mysql> SET @val = FLOOR(RAND() * n) + 1; > mysql> SELECT value FROM table WHERE ID = @val; If two queries is acceptable: select a count() on a unique/primary key, it should minimal overhead since the value is obtained very quickly with those columns. then do a limit... SELECT FLOOR(RAND() * COUNT(id)) + 1 as n FROM table; SELECT value FROM table LIMIT n, 1 return 1 record starting to the nth record. There still lies the performance loss the larger n becomes. Or using the ID method: SELECT FLOOR(RAND() * MAX(id)) + 1 as n FROM table; SELECT value FROM table id >= n LIMIT 1 This might be the optimal in the two query method. Since it will use the index to seek id >= n. Curt -- If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP

« previous php.general (#172226) next »