update in 的优化写法

在一般的 update in 写法就是:

update table_name set column = 'xxx' where column2 in (select x from table_name2 where xxxxxx)

但是这种写法在表数据量小的时候不会有啥问题, 但是在表的数据量比较大的情况下, 这样就会引起全表扫描, 子查询带来了巨大的资源开销,以及锁表.

优化后的写法如下:

update table_a a join table_b b on a.xx=b.xx
set a.xx=要变更的值
where b.xx=条件值

实际例子

第一种写法:

EXPLAIN
UPDATE t_form_template_function SET del_flag = '1' WHERE struct_id IN ( SELECT DISTINCT id FROM t_form_template_struct WHERE pid = 'GE148389280359880457831') and del_flag='0' ;

分析结果为: rows : 6661

第二种写法:

EXPLAIN
UPDATE t_form_template_function f JOIN t_form_template_struct s ON f.struct_id = s.id SET f.del_flag = '1' 
WHERE s.pid = 'GE148389280359880457831' AND f.del_flag = '0';

分析结果为: rows: 6

猜你喜欢

转载自my.oschina.net/zcqshine/blog/1816825
今日推荐