항상 이 서브 쿼리 부분이 헷갈렸는데,
오늘 수업을 들으면서 헷갈렸던 부분들이 많이 정리되었다.
생각보다 간단한 것인 것도 많았는데,
그동안 내가 너무 어렵게 빙빙 꼬아서 접근한 것도 있었던 것 같다😂😀
어려운 상태로 내버려두는 게 아니라 간결하게 간소화해서 학습하는 버릇을 들여야겠다고 다짐🤸♀️🤸♀️
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name) as num_instructors
from department;
서브쿼리의 결과행이 단일하기 때문에 scalar subquery라고 부른다.
연산자 <, >, <>, =
등으로 비교
ex) 스미스의 연봉보다 높은 직원의 이름과 연봉
select ename, sal
from emp
where sal > (select sal from emp where ename ='SMITH')
연산자
IN
, >ANY
, <ANY
, <ALL
, >ALL
, EXIST
부서번호 30인 직원들 중에 가장 연봉을 많이 받는 사원보다 많이 받는 직원 (max로 처리 가능)
select ename, deptno, sal
from emp
where emp.sal > any(select sal from emp where deptno = 30);
select disinct course_id
from section
where semester = 'Fall' and year = 2009 and
course_id in (select course_id from section where semester = 'Spring');
의미적으로 section(table)과 section(table)의 equi-join
in 안에 집합 (다중행 결과)
in (select course_id from section where semester = 'Spring')
select count(distinct ID)
from takes
where (course_id, sec_id, semester, year) in
(select course_id, sec_id, semester, year from teaches where teaches.ID=10101);
의미적으로 TAKES(table)과 Takes(table)의 equi-join
in 안에 집합 (다중행 결과)
비교 대상의 형식이 같아야 한다. course_id, sec_id, semester, year
학생 테이블에서 각 학년별로 최대키를 가진 학생들의 학년과 이름 출력
select name, grade
from student
where (grade, height) in(select grade, max(height) from student group by grade);
select grade, name
from student s1
where height = (select max(height)
from student s2
where s1.grade = s2.grade);
group by
와 같은 효과를 냄코스별 평균 점수 이상인 학생 이름과 코스 이름
select name, title
from student s, course c, takes t
where S.ID = T.ID AND C.course_ID = T.course_id and
score > (select avg(score)
from takes T1
where T1.course_id = C.courseID)
여기서는 C가 튜플 변수가 되어 코스별(수업이름별) 평균 점수를 만들고 해당 점수 이상인 학생과 수업의 이름을 출력한다.
튜플 변수를 이용하는 것 대신 IN을 사용할 수도 있다.
select name, title
from student s, course c, takes t
where S.ID = T.ID AND C.course_ID = T.course_id and
(score) >(select avg(score)
from student
group by score);
select course_id
from section as S
Where semester = 'Fall' and year = 2009 and
exists (select *
from section as T
where semeser = 'Spring' and year = 2010 and S.course_id = T.course_id)
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 as T
where S.ID = T.ID));