在項(xiàng)目開發(fā)中,同事在原本功能的基礎(chǔ)上加入了新的業(yè)務(wù)操作代碼后,導(dǎo)致業(yè)務(wù)操作經(jīng)常超時(shí)椅您。故對(duì)其代碼進(jìn)行調(diào)試跟蹤后定位到,在update數(shù)據(jù)庫(kù)記錄時(shí)寫了in子查詢寡键,完整sql如下(非原sql):
update wms_stock set qty1 = 0 where id in (select stock_id from wms_order_line l where l.a_qty1 = 'a' and l.product_code = 'b');
查看其執(zhí)行計(jì)劃如下:
可以看到select_type存在DEPENDENT SUBQUERY掀泳,即子查詢依賴于外查詢。相當(dāng)于將wms_stock表符合條件的數(shù)據(jù)(這里是全表)查出后西轩,再拿內(nèi)查詢?nèi)ブ饤l匹配是否符合l.stock_id=s.id员舵。故 整個(gè)update語(yǔ)句共需掃描233253*1=233253次。
MySql 官網(wǎng)給出的解決方法是:
If you have a slow 'correlated' subquery with IN, you can optimize it with a join to get around the bug described by Ryan and Stephen. After the optimization the execution time is no longer O(M×N).
按照上邊的思路我們將sql改為:
update wms_stock s join wms_order_line l on s.id = l.stock_id set s.qty1 = 0 where l.a_qty1 = 'a' and l.product_code = 'b';
再次查看執(zhí)行計(jì)劃:
修改后問(wèn)題成功解決藕畔。