php - Randomly get multiple rows from a table -
right i'm selecting 3 random rows table using order rand();
pointed out on web method slow. using on database 30 rows , takes long time return value. of other solutions i've found return 1 row. what's best way return multiple random rows?
$get_projects_query = mysql_query( "select p_id project_data p_featured='1' order rand() limit 3" ) or die(mysql_error()); while($project_row = mysql_fetch_array($get_projects_query)) {?> //do stuff } //end 3 random featured projects loop)
if there 30 rows, have couple other options.
option #1
- fetch 30 rows.
- call shuffle()
- read first 3 off pile
option #2
- generate 3 random numbers 0 29. call them r1, r2, r3.
- select ... p_id in (r1, r2, r3)
option #3
- select p_id ...
- while ($row = mysql_fetch_assoc($result)) $idlist[] = $row["p_id"];
- shuffle($idlist)
- select ... p_id in ($idlist[0], $idlist[1], $idlist[2])
Comments
Post a Comment