1378. Replace Employee ID With The Unique Identifier; LEFT JOIN, IFNULL
https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/
1. Problem
직원 정보가 담긴 Employees 테이블과 고유 ID가 담긴 EmployeeUNI 테이블을 결합해야 한다. 모든 직원의 이름은 출력되어야 하며, 고유 ID가 없는 직원의 경우 그 자리를 NULL로 표시해야 한다. 즉, 정보가 부족하더라도 기준 테이블의 행을 유지하는 것이 핵심이다.
2. Solution: 기준 테이블을 보존하는 외부 조인
모든 직원을 출력하기 위해 Employees를 기준으로 LEFT JOIN을 수행한다. 매칭되는 고유 ID가 없는 경우 SQL 엔진이 자동으로 NULL을 채워준다.
3. Takeaway: 왜 JOIN과 IFNULL의 조합이 오답이었나? (객관적 분석)
- INNER JOIN의 데이터 유실: 단순히 JOIN을 사용하면 양쪽 테이블에 모두 데이터가 있는 '교집합'만 남는다. 고유 ID가 없는 직원은 결과에서 아예 삭제되므로, IFNULL을 써보기도 전에 행 자체가 사라지는 문제가 발생한다.
- 문자열 "null"과 데이터 NULL의 차이:
- 'null'은 4글자로 이루어진 텍스트 데이터이다.
- NULL은 값이 존재하지 않음을 뜻하는 상태값이다.
- 많은 코딩 테스트와 실무 환경에서는 값이 없을 때 공백이나 문자열이 아닌 실제 NULL 상태를 반환하기를 요구한다.
- 출력 별칭(Alias)의 효율성: SELECT 절에서 테이블 별칭(u.unique_id)을 사용하더라도, 최종 출력되는 컬럼명은 별도로 AS를 지정하지 않는 한 원래의 컬럼명(unique_id)을 따른다. 불필요한 별칭 부여를 줄여 쿼리를 간결하게 유지하는 습관은 가독성에 도움이 된다.
Table: Employees
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains the id and the name of an employee in a company.
Table: EmployeeUNI
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| unique_id | int |
+---------------+---------+
(id, unique_id) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the id and the corresponding unique id of an employee in the company.
Write a solution to show the unique ID of each user, If a user does not have a unique ID replace just show null.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Employees table:
+----+----------+
| id | name |
+----+----------+
| 1 | Alice |
| 7 | Bob |
| 11 | Meir |
| 90 | Winston |
| 3 | Jonathan |
+----+----------+
EmployeeUNI table:
+----+-----------+
| id | unique_id |
+----+-----------+
| 3 | 1 |
| 11 | 2 |
| 90 | 3 |
+----+-----------+
Output:
+-----------+----------+
| unique_id | name |
+-----------+----------+
| null | Alice |
| null | Bob |
| 2 | Meir |
| 3 | Winston |
| 1 | Jonathan |
+-----------+----------+
Explanation:
Alice and Bob do not have a unique ID, We will show null instead.
The unique ID of Meir is 2.
The unique ID of Winston is 3.
The unique ID of Jonathan is 1.
1. 정답 쿼리
SELECT u.unique_id, e.name
FROM Employees e
LEFT JOIN EmployeeUNI u ON u.id = e.id;
2. 나의 오답
SELECT IFNULL(u.unique_id, 'null') AS id, e.name AS name
FROM Employees e
JOIN EmployeeUNI u ON u.id = e.id;
아예 IFNULL을 쓰지 말아야 함.
'null' 은 문자열 "null"
문제에서 원하는 건 SQL NULL 값
조인 매칭 안되면 null 처리됨
SELECT 절에 컬럼앞에 붙인 테이블 Alias는 어차피 출력안되니까, Alias 따로 설정할 필요없음
LEFT JOIN해야 unique_id 없는 직원들도 누락없이 출력