2013-02-19 107 views
1

如何优化以下update,因为子查询正在为表a中的每一行执行?如何优化包含“in”子查询的MySQL更新?

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

这是否正确的SQL? – bernie 2013-02-19 17:53:34

+0

参见:http://stackoverflow.com/questions/13011280/if-a-non-correlated-subquery-is-repeated-at-several-places-in-the-query-can-it – DiscoInfiltrator 2013-02-19 18:40:36

回答

2

你可能会使用一个外连接那里有没有符合条件的记录,而不是你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 exists如果您要替换not in,也可以看一下。

我不能告诉你,这会让你的查询更快,但有一些很好的信息here。你必须在你的环境中进行测试。

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