gpt4 book ai didi

MYSQL子查询性能不一致

转载 作者:行者123 更新时间:2023-11-29 13:54:32 25 4
gpt4 key购买 nike

G 日,<​​/p>

我对以下内容感到有些困惑。当我运行此查询时,需要很长时间才能解析:

Select *
from test
where id in (select id from test2 where customer = 'HARRY');

当我单独运行子查询时,它立即解析为“13454”。当我将主查询的 where 语句更改为 in ('13454') 时,它也会立即解析。

有人知道为什么它不能以原始格式运行吗?

干杯,

雷内

最佳答案

原因是 MySQL 的一个怪癖。对外表的每一行执行子查询。

要解决此问题,请使用 exists:

Select *
from test
where exists (select id from test2 where test2.customer = 'HARRY' and test2.id = test.id);

如果您在 test2(customer, id) 上有索引,这将最有效地工作。

我应该补充一点,这取决于 MySQL 的版本(我认为它在 5.5 中已修复)。老的documentation解释为:

Consider the following subquery comparison:

outer_expr IN (SELECT inner_expr FROM ... WHERE subquery_where)

MySQLevaluates queries “from outside to inside.” That is, it first obtainsthe value of the outer expression outer_expr, and then runs thesubquery and captures the rows that it produces.

关于MYSQL子查询性能不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16073005/

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