following the answers i got on this thread PHP MySQL Query to get most popular from two different tables
ive timed the query and im getting disturbing times when calling this query. I get over 8 seconds. afrostarvideos table has about 2000 records,afrostarprofiles about 300records. even after limiting the query to only five. goto http://www.veepiz.com/index.php and check this generation time under popular artists. Please help optimize this query
//Get current time
$mtime = microtime();
//Split seconds and microseconds
$mtime = explode(" ",$mtime);
//Create one value for start time
$mtime = $mtime[1] + $mtime[0];
//Write start time into a variable
$tstart = $mtime;
$q= "SELECT `p`.*, SUM(`v`.`views`)+`p`.`views` AS `totalViews` FROM `afrostarprofiles` `p` LEFT OUTER JOIN `afrostarvideos` `v` ON `p`.`id` = `v`.`artistid`".
"GROUP BY `p`.`id` ORDER BY SUM(`v`.`views`)+`p`.`views` DESC LIMIT $pas_start,$end";
$r=mysql_query($q);
//Get current time as we did at start
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
//Store end time in a variable
$tend = $mtime;
//Calculate the difference
$totaltime = ($tend - $tstart);
//Output result
printf ("Page was generated in %f seconds !", $totaltime);
First thing to know – as soon as you have an
ORDER BY, theLIMITdoesn’t help you.Once MySQL realizes that it needs to order the results before it can limit them, it has to go through the entire table to get all the results before it orders them (and then limits them) for you.
That said (and without seeing the
EXPLAINfor your query [which would be useful]), I’m guessing that most of the time is taken by thatLEFT JOIN.Make sure that there is an index on afrostarprofiles.id (I’m guessing it’s the primary key, so you’re good) and afrostarvideos.artistid.
Also, unless you want to get a result even when there are no matching artists in your second join, I would recommend trying a
JOIN(otherwise known as anINNER JOIN) instead of aLEFT JOIN.