본문 바로가기
DEV/CodingTest

[LeetCode] SQL - 175. Combine Two Tables

by JJHstack 2025. 6. 17.
728x90
반응형

 

이번에 새로운 코딩테스트 사이트를 발견해서 꾸준히 해볼까 합니다.

 

LeetCode의 SQL 문제 중 하나인 175. Combine Two Tables 문제를 풀이하면서 SQL 조인의 기본 개념을 복습해봤습니다. 해당 문제는 LEFT JOIN을 사용하여 두 테이블을 결합하는 간단한 문제입니다.

 

📝 Description

 

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| personId    | int     |
| lastName    | varchar |
| firstName   | varchar |
+-------------+---------+

personId is the primary key (column with unique values) for this table.
This table contains information about the ID of some persons and their first and last names.

 

 

Table: Address

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| addressId   | int     |
| personId    | int     |
| city        | varchar |
| state       | varchar |
+-------------+---------+

addressId is the primary key (column with unique values) for this table.
Each row of this table contains information about the city and state of one person with ID = PersonId.

 

Write a solution to report the first name, last name, city, and state of each person in the Person table. If the address of a personId is not present in the Address table, report null instead.

Return the result table in any order.

The result format is in the following example.

 

 

Example 1:

Input: 
Person table:
+----------+----------+-----------+
| personId | lastName | firstName |
+----------+----------+-----------+
| 1        | Wang     | Allen     |
| 2        | Alice    | Bob       |
+----------+----------+-----------+
Address table:
+-----------+----------+---------------+------------+
| addressId | personId | city          | state      |
+-----------+----------+---------------+------------+
| 1         | 2        | New York City | New York   |
| 2         | 3        | Leetcode      | California |
+-----------+----------+---------------+------------+
Output: 
+-----------+----------+---------------+----------+
| firstName | lastName | city          | state    |
+-----------+----------+---------------+----------+
| Allen     | Wang     | Null          | Null     |
| Bob       | Alice    | New York City | New York |
+-----------+----------+---------------+----------+

Explanation: 
There is no address in the address table for the personId = 1 so we return null in their city and state.
addressId = 1 contains information about the address of personId = 2.

 

 My Code

SELECT
    P.firstName, 
    P.lastName,
    C.city,   
    C.state
FROM Person as P
LEFT JOIN Address as C
ON P.personId = C.personId

 

 

이 문제의 핵심은 LEFT JOIN을 사용하는 것입니다.

  • LEFT JOIN은 왼쪽 테이블(여기서는 Person)의 모든 행을 반환하며, 오른쪽 테이블(Address)에 일치하는 값이 있으면 함께 보여줍니다.
  • 만약 일치하는 값이 없다면, 오른쪽 테이블의 컬럼은 NULL로 반환됩니다.
  • 즉, Address에 정보가 없는 personId에 대해서도 Person에 존재하면 결과에 포함됩니다.

 

간단한 문제지만 조인의 개념을 명확히 잡을 수 있는 좋은 연습문제였습니다.

앞으로 다른 문제들도 블로그에 하나씩 정리해보며 복습해볼 예정입니다 😊

 

궁금한 점이나 피드백은 댓글로 남겨주세요!

728x90
반응형

댓글