php - 使用一个大查询还是多个小查询更快?

标签 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'].'.';

          }

     }

}

最佳答案

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

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

关于php - 使用一个大查询还是多个小查询更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476783/

相关文章:

MySQL Innodb 由于行估计极其错误而无法使用索引

PHP Loop MySQL 结果到数组

php - Twitter Bootstrap - 避免在模态内调整大小

java - 我如何加密和解密在 PHP 和 JAVA 之间使用 AES/GCM/

php - Symfony2 表格 : automatically add NotBlank constraint and Bootstrap Validator message for required fields

php - 使用 php 和 mysql 存储和检索多维数组

php - MySQL : Order by and Group By combining not giving the latest record

php - 使用 MySQL 的 AES_ECRYPT 函数加密一个值,然后使用 PHP 在 URL 字符串中传递它

php - 使用 PHP 从数据库中获取一个变量

javascript - 如何在 PHP 和 Javascript 中保护我的 jQuery AJAX 调用?