Junção Vertical - Operadores sobre conjuntos |
O SQL disponibiliza três operadores que permitem a partir de dois conjuntos produzir um terceiro. Estes operadores actuam sobre as colunas das tabelas de origem, produzindo uma Junção Vertical:
Estes operadores permitem obter um único conjunto resultado a partir de dois conjuntos iniciais. São úteis na junção de diferentes consultas que se refiram a tabelas diferentes mas que tenham colunas com o mesmo tipo de dados. A sua utilizaçãoo segue as seguintes regras:
O operador UNION permite obter a reunião de dois conjuntos:
O comando abaixo apresenta os nomes e salários dos empregados das tabelas EMP e EMPLOYEES. São duas consultas unidas numa única.
select ename, sal from emp UNION select first_name, salary from employees; |
O comando UNION elimina automaticamente as linhas repetidas. Se pretendermos que estas apareçam teremos que utilizar UNION ALL:
select job from emp UNION select job_id from employees; |
JOB ---------- AC_ACCOUNT AC_MGR AD_ASST AD_PRES AD_VP ANALYST CLERK FI_ACCOUNT FI_MGR HR_REP IT_PROG MANAGER MK_MAN MK_REP PRESIDENT PR_REP PU_CLERK PU_MAN SALESMAN SA_MAN SA_REP SH_CLERK ST_CLERK ST_MAN 24 rows selected |
select job from emp UNION ALL select job_id from employees; |
JOB ---------- CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK AC_ACCOUNT AC_MGR AD_ASST AD_PRES AD_VP AD_VP FI_ACCOUNT FI_ACCOUNT FI_ACCOUNT FI_ACCOUNT FI_ACCOUNT FI_MGR HR_REP IT_PROG IT_PROG IT_PROG IT_PROG IT_PROG MK_MAN MK_REP PR_REP PU_CLERK PU_CLERK PU_CLERK PU_CLERK PU_CLERK PU_MAN SA_MAN SA_MAN SA_MAN SA_MAN SA_MAN SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SA_REP SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK SH_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_CLERK ST_MAN ST_MAN ST_MAN ST_MAN ST_MAN 121 rows selected |
O operador INTERSECT permite obter a intersecção entre dois conjuntos:
O comando abaixo permite listar os salários que existem em EMP e em EMPLOYEES:
select sal from emp INTERSECT select salary from employees; |
SAL ---------------------- 3000 1 rows selected |
O operador MINUS permite obter a diferença entre dois conjuntos:
O comando abaixo permite listar os salários que estão em EMP e não estão em EMPLOYEES:
select sal from emp MINUS select salary from employees; |
SAL ---------------------- 800 950 1100 1250 1300 1500 1600 2450 2850 2975 5000 11 rows selected |
Realizado por Turtle Learning ®. Última alteração em 2011-02-26