【问题标题】:mysql performance difference between where id = vs where id IN()mysql在where id = vs where id IN()之间的性能差异
【发布时间】:2015-03-23 11:53:42
【问题描述】:

我对 mysql 很陌生。我有一个查询,从这个查询中我得到了一些 stock_ids。在第二个查询中我需要传递那些 stock_ids。为此,我正在获取数组中的所有 stock_ids。现在我的问题是我可以通过哪种方式将这些 stock_ids 传递给第二个查询。为此,我有两种方法。

First approach:
$array_cnt = count($stockid_array);
for($i = 0; $i<$array_cnt;$i++)
{
$sql = "select reciever_id,sender_identifier,unique_stock_id,vat_number,tax_number from stocktable where stock_id = '".$stockid_array[$i]."'";
// my while loop
}
Another approach is 

$sql = "reciever_id,sender_identifier,unique_stock_id,vat_number,tax_number from stocktable where stock_id in ('1','2','3','4','5','6','7','8','9');
//while loop comes here.

那么哪种方法可以提供良好的性能?请指导我。

【问题讨论】:

  • 第一种方法调用 SQL $array_cnt 次,第二种方法一次 - 猜猜哪个更好?
  • 您有性能问题吗?您看到执行时间或执行计划有什么不同吗?
  • 好的,Smutje,我明白了。谢谢你。和 Jarlh 是的,我在数组计数方面遇到了一些性能问题。

标签: mysql sql join where


【解决方案1】:

MySQL 对in 列表中的常量进行了很好的优化——它基本上对值进行排序并使用二进制搜索。这意味着in 会更快。此外,in 可以利用列上的索引。

此外,运行单个查询应该比运行多个查询更快。

所以,in 版本应该比使用= 运行多个查询更好。

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2013-08-07
    • 2019-09-16
    相关资源
    最近更新 更多