728x90
Subquery
쿼리 구문 안에 쿼리문. group by절 이외에 모두 가능함
select 컬럼명
from 테이블명
where 조건 (select 컬럼명
from 테이블명)
예시
select last_name, salary
from employees
where salary > (select salary from employees where last_name = 'Abel');
select last_name, job_id, salary
from employees
where salary = (select min(salary) from employees);
select department_id, min(salary)
from employees
group by department_id
having min(salary) > (select min(salary) from employees where department_id = 50);
inline view - from절에 subquery가 작성된 경우
select a.last_name, a.salary, a.department_id, b.salavg
from employees a join (select department_id, avg(salary) salavg
from employees
group by department_id) b
on a.department_id = b.department_id
where a.salary > b.salavg;
소속된 부서의 평균 급여보다 자신의 급여가 더 많은 사원만 출력
연습문제
select employee_id, last_name, salary
from employees
where salary >= (select avg(salary) from employees)
order by salary;
고급 subquery
1. 단일행 서브쿼리
서브쿼리로부터 메인 쿼리로 단일행(단일값)이 반환되는 유형
메인 쿼리에 단일행 비교연산자가 필요
단일행 비교연산자 : =, >, >=, <, <=, <>, !=
select last_name, job_id, salary
from employees
where job_id = (select job_id from employees where last_name='Bell')
and salary > (select salary from employees where last_name='Bell');
select last_name, job_id
from employees
where job_id = (select job_id from employees where last_name='Haas');
단일행 서브쿼리로부터 null 값이 반환되는 경우 메인 쿼리결과도 null
2. 다중행 서브쿼리
서브쿼리로부터 메인쿼리로 다중행이 반환되는 유형
메인쿼리에 다중행 비교연산자가 필요함
다중행 비교연산자 : in(= + or), not in(<>+and), 단일행 비교연산자 + any(OR), 단일행 비교연산자 + all(AND)
select employee_id, last_name, job_id, salary
from employees
where salary < any (select salary from employees where job_id ='IT_PROG')
and job_id <> 'IT_PROG';
select employee_id, last_name, job_id, salary
from employees
wehere salary < all (select salary from employees where job_id ='IT_PROG')
and job_id <> 'IT_PROG';
select last_name
from employees
where employee_id not in (select manager_id from employees);
null이 존재하기 때문에 아무런 값이 나오지 않는다.
다중행 서브쿼리로부터 null 값이 반환되는 경우 메인 쿼리에 AND 성격을 가지는 비교연산자를 사용했다면 메인 쿼리 결과도 null
select last_name
from employees
where employee_id not in (select manager_id from employees where manager_id is not null);
조건에 is not null을 작성해주면 정상적으로 출력된다.
즉, null값이 있을 때는 where 조건문에 is not null을 작성해주면 결과가 나타남
728x90
'KDT > DB' 카테고리의 다른 글
240214 DB - DML 2, 트랜잭션 (0) | 2024.02.14 |
---|---|
240207 DB - 고급 Subquery 2, DML 1 (0) | 2024.02.07 |
240131 DB - 고급 JOIN 2 (0) | 2024.01.31 |
240126 DB - JOIN 2, 고급 JOIN 1 (0) | 2024.01.26 |
240110 DB - 그룹함수, JOIN 1 (0) | 2024.01.10 |