使用一个大型查询或几个较小的查询会更快吗?

时间:2014-10-20 23:52:53

标签: php mysql

我一直在思考这个问题,并且认为我会问一些熟悉MySQL甚至PHP的人。假设您有一个查询来获取有关文章的动态信息。您还有几个与文章关联的表格,例如评论和类别。假设在文章结果页面上,您希望获得诸如评论数量和文章类别等信息。哪种方法加载速度更快?

一个大问题:     

$query = "
     SELECT 
          a.article_id, a.title, a.description, a.category_id
          com.comment_id, com.article_id, COUNT(com.article_id) AS num_comments
          cat.category_id, cat.title AS cat_titleca
     FROM articles AS A
     LEFT JOIN categories AS cat ON (a.category_id = cat.category_id)
     LEFT JOIN comments AS com ON (a.article_id = com.comment_id)
     GROUP BY a.article_id
     ORDER BY a.article_id DESC
     LIMIT 10";

if($query = mysql_query($query)){

     if(mysql_num_rows($query) > 0){

          while($article=mysql_fetch_assoc($query)){

              echo $article['title'].' has '.$article['num_comments'].' comments and is in the category '.$article['cat_title'].'.';

          }

     }

}

或者使用几个较小的查询:

<?php

$query_articles = "
     SELECT
          article_id, title, description, category_id
     FROM articles
     ORDER BY article_id DESC
     LIMIT 10";

if($query_articles = mysql_query($query_articles)){

     if(mysql_num_rows($query_articles) > 0){

          while($article=mysql_fetch_assoc($query_articles)){

               $query_comments = "
                    SELECT
                         comment_id, article_id
                    FROM comments
                    WHERE article_id = ".$article['article_id']."
                    ORDER BY comment_id";

               if($query_comments = mysql_query($query_comments)){

                    $num_comments = mysql_num_rows($query_comments);

               }

               $query_cat = "
                    SELECT
                         category_id, title
                    FROM categories
                    WHERE category_id = ".$article['category_id']."
                    LIMIT 1";

               if($query_cat = mysql_query($query_cat)){

                    if(mysql_num_rows($query_cat) > 0){

                         $cat = mysql_fetch_assoc($query_cat);

                    }

                }

                echo $article['title'].' has '.$num_comments.' and is in the category '.$cat['title'].'.';

          }

     }

}

1 个答案:

答案 0 :(得分:4)

单个查询当然更快,为什么不做基准测试

$time = microtime(true);
//code here
$elapsed = microtime(true) - $time;
echo 'Elapsed time = '.$elapsed;