[Database] 9. 서브 쿼리

백하림's avatar
Feb 26, 2025
[Database] 9. 서브 쿼리
-- 서브쿼리 (select안에 select 사용 방법) -- 서브 쿼리 종류 3가지
💡
- 1. 서브 쿼리 (where) -- 중복해서 만들지 않는다. 변경할 때 대처하기 어렵다 -- 연관 관계를 가지게 테이블을 두 개로 만든다. -- (다른 테이블을 참조하는 키를 FK) -- (내 테이블에서 행을 유일하게 결정하는 키)
-- DALLAS에 사는 직원을 출력해주세요 select * from emp where deptno = 20; select deptno from dept where loc = 'dallas'; select * from emp where deptno = (select deptno from dept where loc = 'dallas');
notion image
-- research부서의 직원 출력 select * from dept; select deptno from dept where deptno = 20; select * from emp where deptno = (select deptno from dept where deptno = 20);
notion image
💡
-- 2. 인라인 뷰 (from절에 들어가는 서브 쿼리)
select * from ( select ename, sal*12 '연봉' from emp ) e where e.연봉 = 9600;
notion image
select * from ( select avg(sal) 'avg_sal' from emp group by deptno ) e where e.avg_sal < 2000;
notion image
💡
-- 3. 스칼라 서브 쿼리 (select절에 있는 서브 쿼리)
select * from dept; select * from emp order by deptno; select count(*) from emp where deptno = 10; select d.deptno,d.dname,d.loc, (select count(*) from emp where deptno = d.deptno) '직원수' from dept d;
notion image
Share article

harimmon