mysql连接查询和in的效率取舍

来源:互联网 发布:夏一行 c语言 编辑:程序博客网 时间:2024/06/15 22:35
例如:
A表
id   子id    父id
1      3        2
2      5        2
3      4         3
B表
id    name
3      xxx

5       xxx

首先我要得到a表父id为2的项

在用获得的子id去查B表

连接查询:select name from A right join  B on A.子id =B.id where A.父id='2'   运算时间为:0.562ms

in嵌套查询:select name from B where id in(select A字id from A where A父id=2)运算时间为:0.441ms

相比之下发现in效率更优于连接查询,其实不然我们在来看二句语句连接查询mysql只会执行一次查询,而in会执行2次查询,1句查询和2句差距耗时这就不用比了吧。

结论:in适合小数据量,连接查询大数据量更优,应用时更因该相对玉当下场景来选择。

附上sql语句运算时间计算方法:

//计时开始
runtime();
 
//执行查询
mysql_query($sql);
 
//计时结束.
echo runtime(1);

//计时函数   
function   runtime($mode=0)   {
    static   $t;   
    if(!$mode)   {   
        $t   =   microtime();
        return;
    }   
    $t1   =   microtime();   
    list($m0,$s0)   =   split("   ",$t);   
    list($m1,$s1)   =   split("   ",$t1);   
    return   sprintf("%.3f ms",($s1+$m1-$s0-$m0)*1000);
-此计时函数转于某大虾

0 0