gpt4 book ai didi

mysql - 为什么 NOT IN 条件在 MySQL 中比 IN 慢?

转载 作者:行者123 更新时间:2023-11-29 01:39:47 24 4
gpt4 key购买 nike

几天前,我在接受采访时被问到这个问题。这种缓慢的原因是什么?

最佳答案

根据documentation , in 中的常量列表实现二分查找:

The search for the item then is done using a binary search. This means IN is very quick if the IN value list consists entirely of constants.

没有明确声明 NOT IN 的处理方式相同,但基于此假设是合理的:

  • expr NOT IN (value,...)

This is the same as NOT (expr IN (value,...)).

这将在性能上留下两个可能的差异。首先是索引使用。因为 NOT IN 被记录为本质上使用 IN,所以我希望索引优化是相同的。这是一个预期,但可能不正确。

第二个是 NOT IN 的比较次数少于 IN 的比较次数。这将导致 NOT IN 更快——但考虑到 MySQL 使用的二进制搜索方法,差异小于微观。换句话说,这应该不会有什么不同。

最后,如果您使用的是子查询,那么所有的赌注都没有了。 NOT IN 必须处理整个列表以检查该值是否确实不在列表中。 IN 可以在第一次匹配时停止处理。在某些情况下,这可能会对性能产生影响。

关于mysql - 为什么 NOT IN 条件在 MySQL 中比 IN 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27903969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com