inblog logo
|
jjack1
    MySQL데이터베이스

    [DB] 5. SubQuery

    최재원's avatar
    최재원
    Feb 26, 2025
    [DB] 5. SubQuery
    Contents
    1. 서브쿼리(where절에 들어가는)2. 인라인뷰(from절에 들어가는)3. 스칼라 서브쿼리(select절에 있는) [반복한다]
    ❗
    select안에 select를 사용하는 방법
    종류는 3가지
    • where
    • from
    • select
    ❗
    중복의 문제점
    • 변경에 대처하기 힘들다
    • 메모리 차지
    중복 해결법
    • 연관 관계를 가진 두 개의 테이블로 분리
      • 다른 테이블을 참조하는 키(FK)
      • 내 테이블에서 행을 유일하게 결정하는 키(PK)

    1. 서브쿼리(where절에 들어가는)

    ❗
    값 1개를 가져온다.
    • 댈라스에 사는 직원 출력
    select * from emp where deptno = 20;
    notion image
    select deptno from dept where loc = 'dallas';
    notion image
    select * from emp where deptno = ( select deptno from dept where loc = 'dallas' );
    notion image
    • 리서치부 직원 출력
    select * from emp;
    notion image
    select * from dept;
    notion image
    select *, 'RESEARCH' from emp where deptno = ( select deptno from dept where dname = 'research' );
    notion image

    2. 인라인뷰(from절에 들어가는)

    ❗
    테이블 1개를 가져온다
    select ename, sal*12 '연봉' from emp where 연봉 = 9600; -- 연봉이라는 별칭을 사용하지 못한다. select e.* from ( select ename, sal*12 '연봉' from emp ) e where e.연봉 = 9600;
    notion image
    notion image
    • 미리 view를 만들어서 그 view에서 또 연산하는 방법
    select * from ( select avg(sal) 'avg_sal' from emp group by deptno ) e where e.avg_sal > 2000;
    notion image

    3. 스칼라 서브쿼리(select절에 있는) [반복한다]

    ❗
    새 컬럼을 추가하고 그 데이터를 주입할 때
    본 테이블의 값에 접근할 수 있다
    select이 출력 될 때마다 반복해서 쿼리를 수행한다.
    select d.DEPTNO, d.DNAME, d.LOC, ( select count(*) from emp where deptno = d.deptno ) '직원수' from dept d;
    notion image
    • select문은 커서가 한번 이동할 때 보여줄 값을 찾는다
    • 이 한번 이동할 때 마다 select절을 추가해서 넣으면
    • 컬럼의 값에 접근 가능하다.
    select count(deptno) from emp group by deptno;
    notion image
    select count(*) from emp where deptno = 10;
    notion image
    • 저 숫자 10에 별칭을 넣어 사용할 수 있다
    notion image
    • select문 쿼리 연산 횟수
     
    Share article

    jjack1

    RSS·Powered by Inblog