PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

MYSQL IN 与 EXISTS 的优化示例介绍

原创
2016-06-07 16:28:54 877浏览

优化原则:小表驱动大表,即小的数据集驱动大的数据集。 ############# 原理 (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用法类似。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。