스칼라 서브쿼리 - select 절
인라인 뷰 - from 절
중첩 서브쿼리 - where절
select 절에 사용, 스칼라 서브쿼리의 결과는 하나의 column이어야 함
select case_number,
(select avg(case_number)
from crime_status
where crime_type like '강도' and status_type like '검거') avg
from crime_status
where police_station like '은평' and crime_type like '강도' and status_type like '검거';
from 절에 사용, 메인쿼리에서는 인라인 뷰에서 조회한 column만 사용 가능
select c.police_station, c.crime_type, c.case_number
from crime_status c,
(select police_station, max(case_number) count
from crime_status
where status_type like '발생'
group by police_station ) m
where c.police_station = m.police_station
and c.case_number = m.count;
where 절에 사용, single row, multiple row, multiple column
(1) Single Row Subquery
서브쿼리가 비교연산자와 사용되는 경우 , 서브쿼리의 검색 결과는 한 개의 결과값을 가져와야함.
select name from celeb where name = (select host from snl_show where id = 1);
(2) Multiple Row Subquery
IN - 서브쿼리 결과 중에 포함 될 때
EXISTS - 서브쿼리 결과에 값이 있으면 반환
ANY - 서브쿼리 결과 중에 최소한 하나라도 만족하면 (비교연산자 사용)
ALL - 서브쿼리 결과를 모두 만족하면 (비교연산자 사용)
select host
from snl_shoow
where host in ( select name
from celeb
where job_title like '%영화배우%');
(3) Multiple Column Subquery (연관 서브쿼리)
서브쿼리 내에 메인쿼리 컬럼이 같이 사용되는 경우
select name, sex,agency
from celeb
where (sex, agency) in (select sex agency from celeb where name ='강동원');