[DB.SQL]서브쿼리

HwangBBang·2023년 2월 15일
0
post-thumbnail

서브 쿼리 사용 예시

-- player 선수중에서 서동명 선수와 포지션이 같은 선수는??
-- "=" 을 사용하면 결과 한개만 가능 
select player_name, height, position
from player 
where position = (select position
                  from player
                  where player_name = '서동명');

                  
-- player 선수중에서 박동우 선수와 포지션이 같은 선수는??
-- "in" 을 사용하면 결과 한개만 가능 
select player_name, height, position
from player 
where position in (select position
                  from player
                  where player_name = '박동우');                  

ANY

-- emp 테이블 30번 부서에서 소속된 아무 사원 보다 급여를 더 많이 받는 사원을 조회 
select ename, sal, deptno 
from emp
where sal > any(select sal from emp
                where deptno = 30);     

같은 의미로 Any 을 사용하지 않고 표현 할 수 있다.

 -- emp 테이블 30번 부서에서 소속된 아무 사원 보다 급여를 더 많이 받는 사원을 조회 
select ename, sal, deptno 
from emp
where sal > (select min(sal) from emp
                where deptno = 30);   

ALL

-- emp 테이블 30번 부서에서 소속된 모든 사원 보다 급여를 더 많이 받는 사원을 조회 
select ename, sal, deptno 
from emp
where sal > all(select sal from emp
                where deptno = 30);    

같은 의미로 All 을 사용하지 않고 표현 할 수 있다.

select ename, sal, deptno 
from emp
where sal > (select max(sal) from emp
                where deptno = 30);
 

다중 컬럼 서브퀴리 사용 예시

(player_name'사샤','박동우' 둘 중 하나랑 같으면 돼요)
AND
(position'사샤','박동우' 둘 중 하나랑 같으면 돼요)

select team_id, player_name, height, position
from player 
where team_id in (select team_id from player
                  where player_name in('샤샤', '박동우'))
      and
      position in ( select position from player
                  where player_name in('샤샤', '박동우'));

player_name,position'사샤','박동우' 둘과 같아야 돼요

 
select team_id, player_name, height, position
from player 
where (team_id,position) in ( select team_id,position
                  from player
                  where player_name in('샤샤', '박동우'));
profile
https://hwangbbang.tistory.com/

0개의 댓글