exist | exist [ where ] => where exists 결과 = 서브쿼리가 비어있지 않으면 true를 리턴함 = result set에 투플이 1개라도 있으면 true임 where exists r => r이 공집합이 아니라면 true where not exists r => r이 공집합이라면 true Q) find all courses_id taught in both the Fall 2017 semester and in the Spring 2018 semester => select course_id . from section as S . where semester = “Fall” and year = 2017 and exists ( select * . from section as T where semester = ‘Spring’ and year = 2018 and . S.course_id = T.course_id ); S.course_id 값은 section S 테이블의 투플마다 바뀐다. 하나씩 들어가는거. 이 안에 투플이 1개라도 나오면 TRUE임 - correlation name : outer 쿼리에 있는 변수 S - correlated subquery : inner 쿼리 전까지는 서브쿼리와 outer 쿼리가 독립적이라, 서브쿼리 먼저 실행해 결과로 대체하고 바깥질의 수행했었음 여기선 서브쿼리가 완전히 독립적이지 않음. = 전체 쿼리를 실행하는 데 있어, 서브쿼리가 딱 1회만 수행되는 게 아니라 대체하지 못함 => 서브쿼리가 바깥쪽의 투플 수 만큼 실행됨 Q) find all students’ ID and name of who have taken all courses offered in the Biology department => select distinct S.ID, S.name from student as S where not exists ( ( select course_id . from course . where dept_name = ‘Biology’) except . ( select T.course_id . from takes . where S.ID = T.ID ) ); 학번값 받아 비교하면서, 들은 course_id를 다 뽑는다. 윗부분 코드는 대체 가능함. 값이 투입되어 돌아가지 않으니까. 밑은 안됨 Biology 학과의 course_id들이 수강내역에 있으면 빠진다. 다수강하면 공집합 (biology 학과 course_id) – (학생이 수강한 course_id들) (A가 B에 속하면, A – B 의 결과는 공집합임. 다 빠짐) 이게 매 학생마다 (outer query의 투플 수만큼) 반복된다. not exists => result set에 투플이 1개도 없으면 true가 됨 => 학생마다 반복되므로, 해당 학생이 듣지않은 강의가 없다면 다빼서 공집합이라 true |
'데이터베이스설계' 카테고리의 다른 글
[데이터베이스설계] 3-11 with 절 ( with 테이블명(컬럼명) as (투플 instance 정의) ) (0) | 2025.02.15 |
---|---|
[데이터베이스설계] 3-10 from 절의 sub쿼리 (0) | 2025.02.15 |
[데이터베이스설계] 3-8 set 멤버십 ( in / not in ) (0) | 2024.11.27 |
[데이터베이스설계] 3-7 having절, 중첩 질의문 (0) | 2024.11.26 |
[데이터베이스설계] 3-6 집계함수, group by (0) | 2024.11.25 |