什么时候用 in ?什么时候用 exists ?
跳到导航
跳到搜索
示例
select name
from employees
where empno in
(select distinct empno from job_history);
select name
from employees
where exists
(select empno from job_history where employees.empno=job_history.empno);
如果 employees 中记录数大于 job_history 时,用 in 效率高。
如果 employees 中记录数小于 job_history 时,用 exists 效率高。
注意:在星辰项目遇到过1次关于in的奇怪问题,查询语句的结构比较复杂,但总的来说问题是使用了多重子查询后,in条件失效,没有通过in条件中的子查询把应该筛选出来的数据筛选出来。
以后尽量少用in查询吧,感觉简单的查询、in 中只有比较少的值的时候使用 in 还比较可靠,否则如果 in 里的值是其它子查询的结果还是用连接查询代替吧