Coding/SQL

[LeetCode-SQL 50] 1978. Employees Whose Manager Left the Company

kangplay 2025. 2. 24. 17:56
문제

https://leetcode.com/problems/employees-whose-manager-left-the-company/?envType=study-plan-v2&envId=top-sql-50

설명

manager_id가 employee_id 목록에 없으면서, salary가 $30000 미만인 employee를 구하는 문제이다.

먼저, manager_id가 employee_id 목록에 없는 employee_id를 구하고, 이 서브테이블을 바탕으로 salary 조건으로 최종 결과를 내면 된다. 

Left Join 개념 및 동작 방식
Left Join은 왼쪽 테이블의 모든 행을 유지하면서, 오른쪽 테이블에서 일치하는 데이터를 찾는다. 만약 오른쪽 테이블에 일치하는 데이터가 없으면, 오른쪽 테이블의 컬럼 값들은 NULL로 채워진다.
📌 예제
Employees 테이블
David의 manager_id(10)은 employee_id에 존재하지 않는다.
manager_id로 비교한 테이블의 모든 행은 유지하고, employee_id로 비교된 테이블에서 employee_id가 없으면 null로 되도록 left join을 하면 아래와 같다. 
sql 문
실행 결과
구현
select employee_id
from (
    select e1.*, e2.name as manager_name
    from Employees e1 
    left join Employees e2
    on e1.manager_id = e2.employee_id ) e
where e.salary < 30000 and e.manager_name is null;​
강의 정답 코드

강의에서는 서브쿼리로 모든 employee_id를 추출한 다음, manager_id 가 해당 테이블에 없는지 Not in 을 이용하였다.