gpt4 book ai didi

mysql - 如何优化包含 "in"子查询的 MySQL 更新?

转载 作者:行者123 更新时间:2023-11-29 06:51:45 25 4
gpt4 key购买 nike

如何优化以下update,因为正在为表a中的每一行执行子查询?

update 
a
set
col = 1
where
col_foreign_id not in (select col_foreign_id in b)

最佳答案

您可能会在没有匹配记录的情况下使用外部联接,而不是您的not in:

update table1 a
left join table2 b on a.col_foreign_id = b.col_foreign_id
set a.col = 1
where b.col_foreign_id is null

这应该使用简单的选择类型而不是依赖子查询。

您当前的查询(或实际有效的查询,因为 OP 中的示例看起来不像它)有潜在的危险,因为 b.col_foreign_id 中的 NULL 会导致任何匹配,并且您不会更新行。

如果您想替换 not in

not exists 也是需要注意的地方。

我不能告诉您这会使您的查询更快,但有一些有用的信息 here .您必须在您的环境中进行测试。

这是一个 SQL Fiddle说明 in、exists 和 outer join 之间的区别(检查返回的行、空值处理和执行计划)。

关于mysql - 如何优化包含 "in"子查询的 MySQL 更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14964021/

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