按照我在该线程上得到的答案PHP MySQL Query to get most popular from two different tables

香港专业教育学院定时查询,并在调用此查询时变得不安。我超过8秒。 afrostarvideos表具有约2000条记录,afrostarprofiles约有300条记录。即使将查询限制为仅五个。转到http://www.veepiz.com/index.php并检查流行艺术家的这一代时间。请帮助优化此查询

//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);

最佳答案

首先要知道-一旦有了ORDER BYLIMIT就无济于事。

一旦MySQL意识到需要对结果进行排序才能限制它们,就必须遍历整个表以获取所有结果,然后再为您排序(然后对其进行限制)。

话虽这么说(并且没有看到查询的EXPLAIN [这将很有用]),但我猜测大多数时间都由该LEFT JOIN占用。

确保afrostarprofiles.id和afrostarvideos.artistid上有一个索引(我猜它是主键,所以很好)。

另外,除非您想在第二次加入中没有匹配的艺术家时都得到结果,否则我建议您尝试使用JOIN(否则称为INNER JOIN)而不是LEFT JOIN

07-25 22:53
查看更多