> 文章列表 > mysql in 和 exists 使用目的:先外还是先里

mysql in 和 exists 使用目的:先外还是先里

mysql in 和 exists 使用目的:先外还是先里

 

in

select * from A where id in (select id from B);

先查 select id from B,再查 select * from A where id in()

in先查子表,再查外表

exists

select * from A where id exists (select id from B where B.id = A.id);

exists返回的是true或false,不会返回查到的数据

先执行 select * from A,再将数据放进exists里 select id from B where B.id = A.id 去匹配。子查询匹配到一条,就返回true。最后把所有匹配到的都查出来。

exists先查外表,再查子表。

not exists

exists通常搭配not一起使用,即 not exists。因为效率比not in快。但exists比in慢。

比方说,查询没有员工的部门信息。

select * from dept where not exists ( select id from emp where emp.did = dept.id)

优化原则:数据量小的表驱动数据量大的表。

假设子表数据量大,外表数据量小。优先使用exist。

假设子表数据量小,外表数据量大。优先使用in。
 

MySQL中EXISTS的用法 - QiaoZhi - 博客园 (cnblogs.com)