Skip to main content

サブクエリか join か

概要

  • 目的
    • あるテーブルと紐づいた関連テーブルのキーで絞り込みをしたい
  • 方法
    • IN サブクエリ
    • JOIN + DISTINCT
    • EXISTS (相関サブクエリ)
  • どのケースで便利か
    • IN サブクエリ : 結果が少数で、読みやすさ重視したいとき
    • JOIN + DISTINCT : 複数の列を出力したいとき
    • EXISTS : 存在チェックのみ、件数は気にしないとき

IN サブクエリ

sql
select DEPT_NAME
from DEPT
where DEPT_NO in (
select DEPTNO
from EMP
where JOB = 'XX'
)

JOIN + DISTINCT

sql
select distinct d.DEPT_NAME
from
DEPT d
inner join EMP e
on d.DEPT_NO = E.DEPTNO
where
e.JOB = 'XX'

EXISTS (相関サブクエリ)

sql
select
DEPT_NAME
from
DEPT d
where exists (
select 1 from EMP e
where e.DEPTNO = d.DEPT_NO and e.JOB = 'XX'
)