[SQL] Subquery

MJ·2024년 2월 12일

SQL

목록 보기
19/23

Subquery

1. 서브쿼리?

  • 하나의 SQL문 안에 포함되어 있는 또 다른 SQL문
    메인쿼리가 서브쿼리를 포함하는 종속적인 관계
    서브쿼리는 메인쿼리의 칼럼 사용 가능
    메인 쿼리는 서브 쿼리의 칼럼 사용 불가

2. 사용시 주의

  • subquery는 괄호로 묶어서 사용
  • 단일 행 혹은 복수행 비교 연산자와 함께 사용 가능
  • 서브쿼리에서는 order by 사용 불가

3. 종류

스칼라 서브쿼리 - select 절
인라인 뷰 - from 절
중첩 서브쿼리 - where절


Scalar Subquery

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 '검거';

Inline View

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;

Nested Subquery

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 ='강동원');

0개의 댓글