当前位置:首页 > 数据库 > Mysql

MYSQLIN与EXISTS的优化示例介绍

优化原则:小表驱动大表,即小的数据集驱动大的数据集。 ############# 原理 (rbo) ##################### select * from a where id in (select id from b)等价于:for select id from bfor select * from a where a.id = b.id 当b表的数据集必须小于a表的数

优化原则:小表驱动大表,即小的数据集驱动大的数据集。

############# 原理 (rbo) #####################

select * from a where id in (select id from b) 等价于: for select id from b for select * from a where a.id = b.id

当b表的数据集必须小于a表的数据集时,用in优于exists。

select * from a where exists (select 1 from b where b.id = a.id) 等价于 for select * from a for select * from b where b.id = a.id

当a表的数据集系小于b表的数据集时,用exists优于in。

注意:a表与b表的id字段应建立索引。

例如:

/** 执行时间:0.313s **/ select sql_no_cache * from rocky_member m where exists (select 1 from rocky_vip_appro a where m.id = a.user_id and a.passed = 1); /** 执行时间:0.160s **/ select sql_no_cache * from rocky_member m where m.id in(select id from rocky_vip_appro where passed = 1);

not in 和not exists用法类似。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐