SQL

SELF JOIN + 리트코드 예제

얆생 2025. 1. 10. 20:35

 

  • SELF JOIN은 테이블이 자기 자신과 JOIN하는 것

INNER JOIN을 한다. 대신 동일한 테이블을 사용하는 것이므로 별칭을 다르게 해서 구분하고 각 기준이 되는 key 칼럼을 조인해줘야 함

>> Alias 필수!

 

  • Leetcode 예제 1

https://leetcode.com/problems/employees-earning-more-than-their-managers/

 

181. Employees Earning More Than Their Managers

Table: Employee

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
| salary      | int     |
| managerId   | int     |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.

 

Write a solution to find the employees who earn more than their managers.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Employee table:
+----+-------+--------+-----------+
| id | name  | salary | managerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | Null      |
| 4  | Max   | 90000  | Null      |
+----+-------+--------+-----------+
Output: 
+----------+
| Employee |
+----------+
| Joe      |
+----------+
Explanation: Joe is the only employee who earns more than his manager.

 

문제 이해

- Joe의 매니저는 Sam, Henry의 매니저는 Max인 셈. Joe가 Sam보다 월급이 많고 Henry는 Max보다 월급이 적기에 Joe만출력해주면 되는 문제

 

접근 방식

1. managerId 칼럼 옆에 해당 Id에 맞는 name, salary 정보가 한번 더 붙어야하므로 inner join 사용

2. managerId가 key칼럼으로 오는 테이블에는 manager라는 별칭을 붙여서 조인할 때 헷갈리지 않도록 사용

3. where문에 월급 조건 달기

4. output에 지정된 칼럼명으로 최종 바꿔주기 >> select문에서

 

최종 코드

SELECT Employee.name AS Employee
FROM Employee
     INNER JOIN Employee AS Manager ON Employee.managerId = Manager.id
WHERE Employee.salary > Manager.salary