다른 명령
새 문서: 상위 문서: SQL ==개요== ==각주== 분류:데이터베이스 시스템 |
편집 요약 없음 |
||
| 2번째 줄: | 2번째 줄: | ||
==개요== | ==개요== | ||
'''Subquery'''란, 다른 쿼리 안에 포함된 select-from-where 쿼리를 의미한다. 예를 들면 아래와 같다. | |||
<syntaxhighlight lang="sql"> | |||
select name | |||
from instructor | |||
where dept_name = (select dept_name from department where building = 'Watson'); | |||
</syntaxhighlight> | |||
일반적인 SQL의 쿼리는 다음과 같은 형태를 가진다. | |||
<syntaxhighlight lang="sql"> | |||
select A1, A2, ..., An | |||
from r1, r2, ..., rm | |||
where P | |||
</syntaxhighlight> | |||
이때, subquery는 select, from, where 절에서 사용될 수 있다. | |||
===From 절에서의 Subquery=== | |||
ri 자리에 하나의 서브쿼리를 넣을 수 있으며, 마치 테이블처럼 다룰 수 있다. 이때 subquery에는 as 키워드를 사용하여 별칭 주는 것이 일반적이다. 이는 아래와 같이 사용된다. | |||
<syntaxhighlight lang="sql"> | |||
select * | |||
from (select * from instructor where salary > 50000) as high_paid; | |||
</syntaxhighlight> | |||
===Where 절에서의 Subquery=== | |||
P 자리에 조건식을 쓸 수 있는데, 그 조건식 안에 서브쿼리를 넣을 수 있다. 이때 조건식은 다음과 같이 작성된다. | |||
<syntaxhighlight lang="sql"> | |||
B <operation> (서브쿼리) | |||
</syntaxhighlight> | |||
이때 B는 속성에 해당하며, <operation>은 비교 연산 (=, >, <, in, exists 등)에 해당한다. 이를 바탕으로 where 절에서 subquery는 아래와 같이 사용된다. | |||
<syntaxhighlight lang="sql"> | |||
select name | |||
from instructor | |||
where salary > (select avg(salary) from instructor); | |||
</syntaxhighlight> | |||
===Select 절에서의 Subquery=== | |||
Ai 자리에 단일 값을 반환하는 서브쿼리를 넣을 수 있다. 이는 아래와 같이 사용된다. | |||
<syntaxhighlight lang="sql"> | |||
select name, (select count(*) from teaches where teaches.ID = instructor.ID) as um_courses | |||
from instructor; | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="sql"> | |||
</syntaxhighlight> | |||
==각주== | ==각주== | ||
[[분류:데이터베이스 시스템]] | [[분류:데이터베이스 시스템]] | ||
2025년 4월 2일 (수) 13:21 판
상위 문서: SQL
개요
Subquery란, 다른 쿼리 안에 포함된 select-from-where 쿼리를 의미한다. 예를 들면 아래와 같다.
select name
from instructor
where dept_name = (select dept_name from department where building = 'Watson');
일반적인 SQL의 쿼리는 다음과 같은 형태를 가진다.
select A1, A2, ..., An
from r1, r2, ..., rm
where P
이때, subquery는 select, from, where 절에서 사용될 수 있다.
From 절에서의 Subquery
ri 자리에 하나의 서브쿼리를 넣을 수 있으며, 마치 테이블처럼 다룰 수 있다. 이때 subquery에는 as 키워드를 사용하여 별칭 주는 것이 일반적이다. 이는 아래와 같이 사용된다.
select *
from (select * from instructor where salary > 50000) as high_paid;
Where 절에서의 Subquery
P 자리에 조건식을 쓸 수 있는데, 그 조건식 안에 서브쿼리를 넣을 수 있다. 이때 조건식은 다음과 같이 작성된다.
B <operation> (서브쿼리)
이때 B는 속성에 해당하며, <operation>은 비교 연산 (=, >, <, in, exists 등)에 해당한다. 이를 바탕으로 where 절에서 subquery는 아래와 같이 사용된다.
select name
from instructor
where salary > (select avg(salary) from instructor);
Select 절에서의 Subquery
Ai 자리에 단일 값을 반환하는 서브쿼리를 넣을 수 있다. 이는 아래와 같이 사용된다.
select name, (select count(*) from teaches where teaches.ID = instructor.ID) as um_courses
from instructor;