Wednesday, September 8, 2010

Select Random Rows SQL

Sometimes ago i have a requirement to select random result from MySQL for my website dirjinni. I want to display Random articles at the bottom, as usual i search on google and find a solution which was some thing like...

-- NOT RECOMMENDED --

SELECT id,articles FROM articletable 
ORDER BY RAND() LIMIT 5


i was very happy to get the job done in very short period of time, but i forget there is no short cut to success :).

After 2 or 3 days i realized sometimes the results did not appeared, then i investigate the problem and found out that it is because of that MySQL "RAND()" function, the query become so expensive some times that the query failed and nothing is displayed (as i have shred hosting so resources are limited).

To Solve the problem i first get the MAX id from the table and then use PHP's rand() function to get 5 values from it and then put those values in the "IN" clause of SQL, my PHP code is ...

//...

$maxSQL="select max(id) as MAXIMUM form articletable";

$resultSet=mysql_query($maxSQL);
$arrayAsObject=mysql_fetch_object($resultSet);
$max=$arrayAsObject->MAXIMUM;

$v1=rand(1,$max);
$v2=rand(1,$max);
$v3=rand(1,$max);
$v4=rand(1,$max);
$v5=rand(1,$max);

$randomSQL="SELECT id,article FROM articletable 
            WHERE id 
            IN ($v1,$v2,$v3,$v4,$v5)";
 
//...

if you want more random number you can use array_rand function in PHP but this solve my problem and i hope it solve yours too.

0 comments:

Post a Comment

 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems