2013-02-19 108 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之間的區別(檢查返回的行,空處理和執行計劃)。