[英]Why mysql (not in) faster than without subquery?
I can write a query with two differents types: 我可以用两种不同的类型编写查询:
SELECT *
FROM `pictures`
WHERE `field_id` NOT IN (SELECT `field_id`
FROM `table`
WHERE `confirm` = 0)
and 和
SELECT *
FROM `pictures`
WHERE `field_id` NOT IN (12,56,435,44,25,52,876,99)
But the second example are very faster! 但第二个例子非常快!
What is the reason for being faster? 更快的原因是什么?
Here's a good performance rule of thumb: doing less work takes less time. 这是一个很好的性能经验法则:减少工作时间会减少。
In the simpler example, the MySQL engine executes exactly 1 query: 在更简单的示例中,MySQL引擎正好执行1个查询:
-- Execute the main query (takes time M)
SELECT *
FROM `pictures`
WHERE `field_id` NOT IN (12,56,435,44,25,52,876,99)
In the more complex example, the MySQL engine executes 2 queries: 在更复杂的示例中,MySQL引擎执行2个查询:
-- Execute the subquery (takes time S)
SELECT `field_id` FROM `table` WHERE `confirm` = 0;
-- => (12,56,435,44,25,52,876,99)
-- Plug the subquery results into the main query (takes time M)
SELECT *
FROM `pictures`
WHERE `field_id` NOT IN (12,56,435,44,25,52,876,99);
The simpler example takes about time M
in total, whereas the more complex example takes about time S + M
, plus maybe a bit more overhead to plug everything, and S + M
is greater than M
. 更简单的示例总共花费时间
M
,而更复杂的示例需要时间S + M
,加上插入所有内容可能需要更多开销,并且S + M
大于M
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.