in 안에 서브쿼리 사용 시 주의점

rooni97·2022년 9월 29일
0
select t.* from teacher as t
join center as c on t.center_id = c.id
where t.center_id not in
      (select distinct t2.center_id  from user as u
      join teacher t2 on u.id = t2.id
      where u.auth = 'DIRECTOR');
  • 위의 쿼리 실행의 결과 row 수가 0이 나온다.
select distinct t2.center_id
from user as u
join teacher t2 on u.id = t2.id
where u.auth = 'DIRECTOR';

select distinct c.id
from teacher as t
join center as c on t.center_id = c.id;

  • not in 쿼리로 3개 중 2개를 제외한 1개의 id에 해당하는 값이 나와야되는데 안나옴
  • NOT IN문 서브쿼리의 결과 중에 NULL이 포함되는 경우 데이터가 출력되지 않는다.
  • 따라서 is not null 조건을 추가해줘야 한다!
select t.* from teacher t
where t.center_id not in
(select distinct t2.center_id
from user as u
join teacher t2 on u.id = t2.id
where u.auth = 'DIRECTOR' and t2.center_id is not null);
  • is not null 조건을 추가하면 정상적으로 결과가 출력된다.

레퍼런스
https://aljjabaegi.tistory.com/459 [알짜배기 프로그래머:티스토리]

0개의 댓글