简体   繁体   English

MySQL的性能差异之间的地方ID =与地方ID IN()

[英]mysql performance difference between where id = vs where id IN()

I am very new to mysql . 我是mysql的新手。 I had a query, from this query i am getting some stock_ids.In the second query i need to pass those stock_ids. 我有一个查询,从这个查询中我得到一些stock_ids。在第二个查询中,我需要传递那些stock_ids。 For this i am fetching all the stock_ids in a array.Now my question is in which way can i pass those stock_ids to the second query. 为此,我正在获取数组中的所有stock_ids。现在我的问题是我可以通过哪种方式将这些stock_ids传递给第二个查询。 For this i have two approaches. 为此,我有两种方法。

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.

So which approach gives good performance ? 那么哪种方法可以提供良好的性能呢? Please guide me. 请指导我。

MySQL has a nice optimization for constants in an in list -- it basically sorts the values and uses a binary search. MySQL对in列表中的常量进行了很好的优化-它基本上对值进行排序并使用二进制搜索。 That means that the in is going to be faster. 这意味着, in将要更快。 Also, in can take advantage of an index on the column. 同样, in可以利用列上的索引。

In addition, running a single query should be faster than running multiple queries. 此外,运行单个查询应该比运行多个查询更快。

So, the in version should be better than running multiple queries with = . 因此, in版本应该比使用=运行多个查询更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM