NOT IN/EXISTS in more than one table in the same query

Asked

Viewed 20 times

0

I have a table of employees and I need to extract from it a query of employees who are not registered in any of the positions (architect, landscaper and manager). The column COD of employee is the primary key of all other posts in tables.

table employee

COD | NOME
1   | joão
2   | maria
3   | josé
4   | paulo
5   | pedro

table: architect

COD | PROJETO
1     336B

table: landscaper

COD | PROJETO
3     1052

table: manager

COD | PROJETO
4     450

I tried to use the strategy of nesting the queries bringing me only people registered in the positions and then performing a select with NOT IN, so would have only employees who are not in those positions

SELECT empregado.cod
WHERE EXISTS (SELECT arquiteto.cod)

Only I would need to validate the 3 tables in a single query. Someone suggests me what is the best strategy to return employees without posts?

1 answer

0


Although the modeling is very strange try:

SELECT empregado.cod
WHERE NOT EXISTS 
      (SELECT cod FROM arquiteto WHERE empregado.cod = arquiteto.cod 
       UNION
       SELECT cod FROM paisagista WHERE empregado.cod = paisagista.cod
       UNION
       SELECT cod FROM gerente WHERE empregado.cod = gerente.cod)

or

SELECT empregado.cod
WHERE NOT IN (SELECT cod FROM arquiteto
              UNION
              SELECT cod FROM paisagista
              UNION
              SELECT cod FROM gerente)
  • Hello, I just made a few adjustments here but your guidance did work. I VERY agree that the modeling is bizarre kk.

  • Settings: SELECT employee.Cod FROM employee WHERE employee.Cod NOT IN (SELECT Cod FROM ARCHITECT Where employee.Cod = architect.Cod UNION SELECT Cod FROM landscaper WHERE employee.Cod = landscaper.Cod UNION SELECT Cod FROM manager WHERE employee.Cod = manager.Cod)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.