inblog logo
|
gyul
    데이터 베이스

    [데이터 베이스] 5. Subquery (서브 쿼리)

    귤's avatar
    귤
    Feb 26, 2025
    [데이터 베이스] 5. Subquery (서브 쿼리)
    Contents
    1. 서브 쿼리2. 인라인 뷰3. 스칼라 서브 쿼리

    1. 서브 쿼리

    💡
    한 쿼리 내에 포함된 또 하나의 쿼리

    ✅ where 절의 서브 쿼리

    💡
    • 서브 쿼리는 where 절에서 사용하는 쿼리이다.
    • 서브 쿼리의 결과가 단일행이면 단일행 서브 쿼리, 복수행이면 복수행 서브 쿼리라 부른다.
    -- 서브 쿼리 -- 1. 서브 쿼리 (where 자리에 들어가는 것 (첫번째줄에 있음)) -- 중복해서 안 만든다. 변경에 대처하기 힘들다. -- 연관 관계를 가지게 된 테이블을 두개로 만든다. -- (다른 테이블을 참조하는 키를 FK) -- (내 테이블에서 행을 유일하게 결정하는 키 PK) -- DALLAS에 사는 직원을 출력해주세요. -- 1. select * from emp where deptno = 20; -- 2. select deptno from Dept where loc = 'DALLAS'; -- 3. select * from emp where deptno = (select deptno from Dept where loc = 'DALLAS');
    notion image

    ✅ where 절의 서브 쿼리 예제

    -- RESEARCH 부서의 직원을 출력해주세요. select * from Dept; select * from emp; select * from dept where DEPTNO = 20; select * from emp where deptno = (select deptno from dept where DEPTNO = 20); ------------------------------------------------------ select * from student; select * from professor; select profno from student where name = '김재수'; select * from professor where profno = (select profno from student where name = '김재수');
    notion image
    notion image

    2. 인라인 뷰

    select ENAME, sal*12 '연봉' from emp where 연봉 = 9600;
    • 실행이 안됨 → 이유는 select절 보다 where이 먼저 실행되서 이해를 하지 못하기 때문

    ✅ from 절의 서브 쿼리

    💡
    • 인라인 뷰는 from 절에 사용되는 서브 쿼리이다.
    • 인라인 뷰는 하나의 임시 테이블이라고 생각하면 된다.
    • 메인 쿼리에서는 인라인 뷰에서 select한 컬럼만 사용 가능하다.
    -- 2. 인라인 뷰 (from 절에 들어가는 subquery) -> 얘를 사용하는 이유는? - 퍼올린 테이블을 다시 테이블로 사용하려고 select ENAME, sal*12 '연봉' from emp where 연봉 = 9600; select e.* from ( select ENAME, sal*12 '연봉' from emp ) e where e.연봉 = 9600; -- having을 사용한 것과 같음 select * from ( select avg(sal) 'avg_sal' from emp group by deptno ) e where e.avg_sal < 2000;
    notion image
    notion image

    3. 스칼라 서브 쿼리

    select d.*, (select * from emp) -- 이중 for문이라고 생각하자. 바깥 for문은 몇번 도는가? - 4번, 안쪽 for문은 몇번 도는가? - 14번 from dept d;
    notion image
    • 순차적으로 찾아내는 것 = 시퀀셜 (sequential)
    • 정렬 하는 방법 : order by (select절 보다 더 늦게 실행됨, 하지만 정렬할 수 있어서 일단 알기만 하기)

    ✅ Select 절의 서브 쿼리

    💡
    • select 절에서 사용하는 서브 쿼리이다.
    • 스칼라는 한 번에 한 가지만 처리하는 이라는 뜻을 가지고 있다. 즉, 스칼라 서브 쿼리에 의해 나오는 결과는 하나의 행이어야 한다.
    -- 3. 스칼라 서브쿼리 (select 절에 있는 subquery) + 결과값이 꼭 하나여야 한다 select * from emp order by deptno; select d.DEPTNO, d.dname, d.loc, (select count(*) from emp where deptno = d.deptno) '직원수' -- 별칭을 통해서 커서 값을 넣을 수 있다 '(d.deptno)' 이 자리에 from dept d; ---------------------- 직원 수 계산한 값 select count(*) from emp where deptno = 10;
    notion image
     
    Share article

    gyul

    RSS·Powered by Inblog