当前位置: 移动技术网 > IT编程>数据库>Mysql > MYSQL IN 与 EXISTS 的优化示例介绍

MYSQL IN 与 EXISTS 的优化示例介绍

2017年12月12日  | 移动技术网IT编程  | 我要评论

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

############# 原理 (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用法类似。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网