剔除那些没有分配员工的部门
我想编写一个sql查询,并想从DEPT表中获取在EMP表中没有分配员工的部门名称。
表结构:
EMP
EMPNO ENAME DEPTNO
DEPT
DEPTNO DNAME
所以我想知道那些没有员工协会的DEPT。
I want to write an sql query , and want to get the dept name from DEPT table who has no employees assigned in EMP table.
Table Structure:
EMP
EMPNO ENAME DEPTNO
DEPT
DEPTNO DNAME
So I like to know those DEPT who has no employees association.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
只有 NOT EXISTS
或 EXCEPT 才是正确的,在这种情况下更复杂
两者都应该给出相同的计划(带有左反半连接)
其他答案的注释:
A LEFT JOIN 将给出一行每个员工。你需要 DISTINCT。与 NOT EXISTS 相比,这会损害计划。
所以通常应该使用 NOT EXISTS 或 EXCEPT
It's only correct with NOT EXISTS
or EXCEPT, more complex in this case
Both should give the same plan (with a left anti semi join)
Notes on other answers:
A LEFT JOIN will give one row per employee. You'd need DISTINCT. Which compromises the plan compared with NOT EXISTS
NOT IN will give false results if there is an Employee who has no Department. NOT IN with a NULL in the list fails
So generally one should use NOT EXISTS or EXCEPT
更新:
@bernd_k 指出
DISTINCT
是不必要的(SELECTDISTINCTD.DNAME ...)这种情况 - 即使没有它,也不会返回重复的部门。UPDATE:
@bernd_k pointed out that
DISTINCT
is not necessary (SELECTDISTINCTD.DNAME ...) in this case - even without it no duplicate departments will be returned.您可以从 dept 表中选择 emp 表中没有的编号:
You can select these departments from dept table whom numbers are not present in emp table:
子查询用于获取与某个部门关联的所有员工:
not in
将给出不属于任何部门的员工。The sub query is used to get all the employees who are associated with a department:
not in
will give the employees who do not belong to any department.下面没有使用任何 except 或 not ,并且性能方面更好
The below is not using any except or not in and performance wise it is better
查找不包含job_id ST_MAN 的部门的department_id
Find department_id for departments that do not contain the job_id ST_MAN