1.2 - Sub Consultas

  • View
    11

  • Download
    4

Embed Size (px)

Text of 1.2 - Sub Consultas

6/5/2010

Sub-ConsultasCludio Ratke

Conceitos

Uma subconsulta uma instruo SELECT que incorporada em outra instruo SELECT.

ExemplosWHERE

SELECT FROM WHEREFIELD_LIST

lista_select tabela(s) operador (SELECT lista_select colunax FROM tabela); lista_select, (SELECT lista_select xFROM tabela) tabela(s) lista_select (SELECT xFROM

SELECT FROM

FROM

SELECT FROM

tabela)

HAVING

SELECT lista_select, FUNCTION FROM tabela(s) GROUP BY lista_select HAVING FUNCTION (SELECT xFROM tabela)

1

6/5/2010

Usando Sub-Consulta na clusula WhereSELECT ename FROM emp WHERE sal >2975

(SELECT sal FROM emp WHERE empno=7566);

salrio do funcionrio 7566. A consulta externa obtm o resultado da consulta interna e o utiliza para exibir todos os funcionrios que recebem mais que essa quantia

Usando Sub-Consultas na clusula WhereSELECT FROM WHERE ename, job emp job = (SELECT FROM WHERE sal > (SELECT FROM WHERE

CLERK

job emp empno = 7369)1100

AND

sal emp empno = 7876);

Usando Sub-Consulta na clusula WhereSELECT FROM WHERE ename, job, sal emp 800 sal = (SELECT MIN(sal) FROM emp);

2

6/5/2010

Usando Sub-Consulta na clusula WhereSELECT ename, sal FROM emp WHERE (job, deptno) in (SELECT job, deptno FROM emp WHERE ename = 'ALLEN')

Usando Sub-Consulta na clusula FromSELECT a.ename, a.sal, a.deptno FROM (SELECT * FROM emp) a

SELECT a.ename, a.sal, a.deptno, b.salavg FROM emp a JOIN (SELECT deptno, avg(sal) salavg FROM emp GROUP BY deptno) b USING (deptno) WHERE a.sal > b.salavg;

Usando Sub-Consulta - clusula HavingSELECT deptno, MIN(sal) FROM emp GROUP BY deptno HAVING MIN(sal) > (SELECT MIN(sal) FROM emp WHERE deptno = 20);

3