MYSQL IN 与 EXISTS 的优化示例介绍

优化原则:小表驱动大表,即小的数据集驱动大的数据集。 ############# 原理 (RBO) ##################### select from A where id in (select id from B)等价于:for select id from Bfor select from A where A.id = B.i

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

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