Utilizando "exception join" em SQL
Um exception join retorna apenas os registros da primeira tabela que não possuem um registro correspondente (de acordo com a condição) na segunda tabela.
A sintaxe do “exception join” do SQL é difícil de ser entendida e raramente é utilizada. Nesta dica veremos como trabalhar com este comando SQL através dois exemplos.
Considere as duas tabelas seguintes:
> select * from employee
EMPLOYEEID EMPLOYEENAMEDEPARTMENTID
1 Greg Graffin1
2 Dino Cazares2
3
4 Lee Ving4
5 Mike Levine4
6 Devin Townsend6
7 Otep Shamaya7
> select * from department
DEPARTMENTID DEPARTMENTNAME
1HR
2IS
3QA
4CR
Para encontrar os empregados com um departamento inválido faça:
> select
Employee.employeeName
from
Employee
exception join
Department
on
Employee.departmentID = Department.departmentID
EMPLOYEENAME
Devin Townsend
Otep Shamaya
Para encontrar os departamentos que não contêm empregados, faça:
> select
Department.departmentName,
Department.departmentID
from
Department
exception join
Employee
on
Employee.departmentID = Department.departmentID
DEPARTMENTNAME DEPARTMENTID
QA 3
O comando exception join é funcionalmente equivalente a:
SELECT
Employee.employeeName
FROM
Employee
where
not exists
(select * from Department
where Employee.departmentID = Department.departmentID)
ou
> select
Employee.employeeName
from
Employee
where
Employee.departmentID not in
(select departmentID from Department)