多个小查询与单个长查询。哪一个更有效率?

时间:2013-04-08 09:02:12

标签: mysql

以下哪一项更有效:

  1. 单个较长的查询:

    "SELECT COUNT( * ) AS num
    FROM (
    
        SELECT users.UID, cnumber
        FROM users
        JOIN identity ON users.UID = identity.UID
        WHERE  'abc'
        IN (google, facebook, twitter, linkedin)
    
    ) AS userfound
    JOIN jobs ON userfound.cnumber = jobs.cnumber
    WHERE JID = 24";
    
    
    if(resultfromquery == 1)
        //Some code here
    else
        //Some code here
    
  2. 将较长的查询分解为多个单表查询:

    uid = "SELECT UID FROM identity WHERE 'abc' IN (google, facebook, twitter, linkedin)";
    cnumber_from_usertable = "SELECT cnumber FROM users WHERE UID = 'uid'";
    cnumber_from_jobtable = "SELECT cnumber FROM jobs WHERE JID = 24";
    
    if(cnumber_from_usertable == cnumber_from_jobtable)
        //Some code here
    else
        //Some code here
    

2 个答案:

答案 0 :(得分:6)

测量微量时差;-) 我会选择单一查询,更少的连接,更少的等待时间,它旨在处理这类事情。

http://www.phpjabbers.com/measuring-php-page-load-time-php17.html

<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
?>
"SELECT COUNT( * ) AS
FROM (

    SELECT users.UID, cnumber
    FROM users
    JOIN identity ON users.UID = identity.UID
    WHERE  'abc'
    IN (google, facebook, twitter, linkedin)

) AS userfound
JOIN jobs ON userfound.cnumber = jobs.cnumber
WHERE JID = 24";


if(resultfromquery == 1)
    //Some code here
else
    //Some code here

<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
echo 'Page generated in '.$total_time.' seconds.';
?>

答案 1 :(得分:3)

其实我对此有不同的看法。 MYSQL支持子查询,其中一个原因就是将较大的查询分解为较小的查询。如果您正在使用INNODB引擎并正确使用参数,例如tmp table,heap table,bufferpool或query cache,那么您可能会获得比较小查询更好的结果。 MYSQL旨在执行大量的小查询,因此最好有更多的小查询,然后是更大的查询。

如果更大的查询是更好的选择,那么我们就不需要创建像Infinidb和INfobright这样的工具,它使用基于列的结构来运行大型查询,而MYSQL是基于行的。

所以考虑一下,小查询会比单个查询更好,而且开销不是查询连接,而且连接MYSQL非常便宜所以不用担心它们。如果您的MYSQL正在创建线程,那么就不用担心了。

总之,我会选择少量查询与巨型大型查询。