Last updated on January 21st, 2025 at 11:01 pm
Here, we see the Combine Two Tables LeetCode Solution. This Leetcode problem is solved using MySQL and Pandas.
List of all LeetCode Solution
Level of Question
Easy
Combine Two Tables LeetCode Solution
Table of Contents
1. Problem Statement
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.
Column Name | Type |
PersonId | int |
FirstName | varchar |
LastName | varchar |
PersonId is the primary key column for this table.
Column Name | Type |
AddressId | int |
PersonId | int |
City | varchar |
State | varchar |
AddressId is the primary key column for this table.
The result format is in the following example.
Example 1:
Input:
personId | lastName | firstName |
1 | Wang | Allen |
2 | Alice | Bob |
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.
2. Code Implementation in Different Languages
2.1 Combine Two Tables MySQL
select FirstName, LastName, City, State from Person as p left join Address as a on p.PersonId = a.PersonId;
2.2 Combine Two Tables Pandas
import pandas as pd def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFrame: result = pd.merge(person, address, on='personId', how='left') result = result[['firstName', 'lastName', 'city', 'state']] return result