我需要确定这一点,所以我对这两种方法都进行了基准测试。我始终发现IN比OR要快得多。
不要相信那些发表“意见”的人,科学就是测试和证据。
我运行了1000倍的等效查询循环(为了一致性,我使用sql_no_cache):
: 2.34969592094秒
或者:5.83781504631秒
更新:
(我没有原始测试的源代码,因为它是6年前的,尽管它返回的结果与此测试相同)
为了要求一些示例代码来测试这一点,这里是最简单的可能用例。使用Eloquent来简化语法,原始的SQL等价执行相同的操作。
$t = microtime(true);
for($i=0; $i<10000; $i++):
$q = DB::table('users')->where('id',1)
->orWhere('id',2)
->orWhere('id',3)
->orWhere('id',4)
->orWhere('id',5)
->orWhere('id',6)
->orWhere('id',7)
->orWhere('id',8)
->orWhere('id',9)
->orWhere('id',10)
->orWhere('id',11)
->orWhere('id',12)
->orWhere('id',13)
->orWhere('id',14)
->orWhere('id',15)
->orWhere('id',16)
->orWhere('id',17)
->orWhere('id',18)
->orWhere('id',19)
->orWhere('id',20)->get();
endfor;
$t2 = microtime(true);
echo $t."\n".$t2."\n".($t2-$t)."\n";
1482080514.3635
1482080517.3713
3.0078368186951
$t = microtime(true);
for($i=0; $i<10000; $i++):
$q = DB::table('users')->whereIn('id',[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])->get();
endfor;
$t2 = microtime(true);
echo $t."\n".$t2."\n".($t2-$t)."\n";
1482080534.0185
1482080536.178
2.1595389842987