php - MySQL get a random value between two values -
i have 2 columns in row: min_value
, max_value
. there way select like:
select rand(`min_v`, `max_v`) `foo` [..]
i realize rand
different thing; closest came (with help) (rand() * (max-min))+min
, though produce float number, i'd need round() , wrong.
unless can suggest alternative (which useful), go php way.
actually, round((rand() * (max-min))+min)
best way in mysql you'd like. best way in actionscript, javascript, , python. honestly, prefer php way because more convenient.
because don't know how many rows you'll returning, can't advise whether better use php or mysql this, if you're dealing large number of values better off using mysql.
addendum
so, there question whether better in php or mysql. instead of getting debate on principles, ran following:
<pre><?php $c = mysql_connect('localhost', 'root', ''); if(!$c) die('!'); echo mysql_select_db('test', $c)?'connection':'failure'; echo php_eol; echo ':::::::::::::::::::::::::beginning mysql rand::::::::::::::::::::::::::::::'.php_eol; $start = microtime(1); for( $i = 0; $i < 100000; $i++ ) { $r = mysql_query( 'select round(rand() * (200-10) + 10) dual' ); $r = mysql_fetch_array( $r ); } $end = microtime(1); echo ($end - $start) . " mysql select".php_eol; echo ':::::::::::::::::::::::::beginning php rand::::::::::::::::::::::::::::::' .php_eol; $start = microtime(1); for( $i = 0; $i < 100000; $i++ ) { $r = mysql_query( 'select 200 two, 10 tem dual' ); $r = mysql_fetch_array( $r ); $r[2]= rand($r[0], $r[1]); } $end = microtime(1); echo ($end - $start) . " php select".php_eol;
mysql faster 2-3%.
if use this, (note, more columns return mysql):
<pre><?php $c = mysql_connect('localhost', 'root', ''); if(!$c) die('!'); echo mysql_select_db('test', $c)?'connection':'failure'; echo php_eol; echo ':::::::::::::::::::::::::beginning mysql rand::::::::::::::::::::::::::::::'.php_eol; $start = microtime(1); for( $i = 0; $i < 100000; $i++ ) { $r = mysql_query( 'select round(rand() * (200-10) + 10) rd, 200 two, 10 ten dual' ); $r = mysql_fetch_array( $r ); } $end = microtime(1); echo ($end - $start) . " mysql select".php_eol; echo ':::::::::::::::::::::::::beginning php rand::::::::::::::::::::::::::::::' .php_eol; $start = microtime(1); for( $i = 0; $i < 100000; $i++ ) { $r = mysql_query( 'select 200 two, 10 tem dual' ); $r = mysql_fetch_array( $r ); $r[2]= rand($r[0], $r[1]); } $end = microtime(1); echo ($end - $start) . " php select".php_eol;
mysql comes out behind 3-4% (very inconsistent results) (about same results if don't use array index assignment $r[2]).
the major difference, seems, comes number of records return php , not randomization system itself. so, if need column a, column b, , random value, use php. if need random value, use mysql.
Comments
Post a Comment