전공/데이터베이스

[데이터베이스] #7 SQL IV (중첩 서브질의)

Campus Coder 2024. 5. 20. 09:57
728x90
반응형

목차

  1. IN 연산자
  2. 비교 연산자
  3. 상관 서브질의
  4. exists 구성요소 
  5. for all
  6. unique 구성요소
  7. from 절 서브질의
  8. lateral 절
  9. with 절
  10. Scalar 서브질의

1. IN 연산자

단일 값이 다수 값에 속하는가를 검사

값이 하나가 아니고 여러 개로 구성되는 형태도 in 연산 적용 가능

Select name, salary
from professor
where pID in (10, 21, 22);

pID 값으로 10, 21, 22 중 하나를 가지는 professor의 정보 반환

Select distinct cID
from teaches
where semester = 'Fall' and year = 2009 and
cID not in (	select cID from teaches
		where semester = 'Spring' and year = 2010);

2010년 봄에 강의하지 않았으며 2009년 가을에 강의한 과목의 cID

2. 비교 연산자

some(any), all

5 ≠ some (0, 5) = true

#하나라도 같지 않은 항목이 존재

5 ≠ all (6, 7) = true

#모든 항목이 같지 않아서 참임

Select name
from professor
where salary > all (	select salary
			from professor
			where deptName='CS');

3. 상관 서브질의

내부 중첩질의에서 외부 테이블을 참조하는 것

내부 중첩질의를 외부 테이블의 각 터플 값에 대하여 수행하여야 함

수행 시간이 많이 소요됨

4. exists 구성요소

인자 형태로 표현되는 서브질의의 결과가 존재하면 참을 반환

즉 내부질의를 수행하여 결과 터플이 반환되면 exists 표현은 참임

Select S.cID
from teaches as S
where S.smemster = 'Fall' and S.year = 2009 and
exists(	select *
	from teacher as T
	where T.semester = 'Fall' and T.year = 2010
		and S.cID = T.cID);

교집합이나 where 절에서 선택과 조인을 하는 것이 더 효율적임

5. for all

Select S.sID, S.name
from student as S
where not exists ((	select cID
			from course
			where deptName = 'CS')
except (select T.cID
	from takes as T
	where S.sID = T.sID));

(CS 과목 - 학생이 수강한 과목)의 집합이 존재하지 않는 학생

즉, 듣지 않은 CS 과목이 없는 학생

즉, 모든 CS 과목을 수강한 학생

6. unique 구성요소

unique 구성요소는 인자형식으로 표현되는 서브질의 결과에 중복성이 있는지를 검사

unique(r)에서 r이 공집합이면(즉, 질의 결과가 없으면) unique(r)은 참임

터플 중의 속성이 한 개라도 널 값을 가지면 동일하지 않다고 판별

unique {<1, null>, <1, null>} : true

7. from 절 서브질의

Select max(totalSalary)
from (	select deptName, sum(salary)
	from professor
	group by deptName) as deptTot(deptName, totalSalary);

8. lateral 절

from 절에서 선행 관계 또는 서브질의를 참조하게 함

Select P1.name, P1.salary, avgSalary
from professor P1, lateral (	select avg(P2.salary) as avgSalary
				from professor P2
				where P1.deptName= P2.deptName);

name, salary, avgSalary를 구하는 문장

Select name, salary, avg(salary) //syntax error
from professor
group by deptName;

name, salary의 개수와 avg(salary)의 개수가 달라서 오류

9. with 절

SQL 문장의 결과를 임시적으로 저장

With	maxBudget(value) as
		(select max(budget)
		from department)
select deptName, budget
from departmant, maxBudget
where department.budget = maxBudget.value;

departmant에서 budget의 최댓값을 구함

10. Scalar 서브질의

서브질의가 오직 한개 속성을 반환하고 속성 값으로 한 개 값을 반환한다면,

연산 식에서 값이 반환되는 어떤 곳이라도 서브질의가 나타날 수 있음

728x90
반응형