“什么时候用 in ?什么时候用 exists ?”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (建立内容为“1”的新页面) |
Jihongchang(讨论 | 贡献) |
||
(未显示同一用户的1个中间版本) | |||
第1行: | 第1行: | ||
− | + | === 示例 === | |
+ | <syntaxhighlight lang="sql"> | ||
+ | select name | ||
+ | from employees | ||
+ | where empno in | ||
+ | (select distinct empno from job_history); | ||
+ | </syntaxhighlight><syntaxhighlight lang="sql"> | ||
+ | select name | ||
+ | from employees | ||
+ | where exists | ||
+ | (select empno from job_history where employees.empno=job_history.empno); | ||
+ | </syntaxhighlight>如果 employees 中记录数大于 job_history 时,用 in 效率高。 | ||
+ | |||
+ | 如果 employees 中记录数小于 job_history 时,用 exists 效率高。 | ||
+ | |||
+ | 注意:在星辰项目遇到过1次关于in的奇怪问题,查询语句的结构比较复杂,但总的来说问题是使用了多重子查询后,in条件失效,没有通过in条件中的子查询把应该筛选出来的数据筛选出来。 | ||
+ | |||
+ | 以后尽量少用in查询吧,感觉简单的查询、in 中只有比较少的值的时候使用 in 还比较可靠,否则如果 in 里的值是其它子查询的结果还是用连接查询代替吧 |
2024年11月14日 (四) 08:38的最新版本
示例
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 里的值是其它子查询的结果还是用连接查询代替吧