php - Mysql select 查询超过 8 秒但限制为 5 条记录

标签 php mysql

按照我在这个帖子上得到的答案 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

关于php - Mysql select 查询超过 8 秒但限制为 5 条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4536540/

相关文章:

php - 如何在 ZF2 中为使用 Sql 对象创建的 Sql 语句的结果集设置数组对象原型(prototype)

php - 将文本文件每行上传到 mysql 行

php - 如何比较mysql中一张表中具有相同值但效果不同的两个字段?

php - 整合MySQL查询结果

WHERE 中的 MySQL IF/ELSE 语句

php - 中文条码打印机和 Linux

php - 所有 PHP 相等比较都是对称的吗?

php - 结合 sprintf 和 IF 条件

php - MySQL-排序后插入行

c# - 具有多个查询的 MySql .NET 连接器不接受事务