Combine Two Tables LeetCode Solution

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

Combine Two Tables LeetCode Solution

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 NameType
PersonIdint
FirstNamevarchar
LastNamevarchar
Table: Person
PersonId is the primary key column for this table.
Column NameType
AddressIdint
PersonIdint
Cityvarchar
Statevarchar
Table: Address
AddressId is the primary key column for this table.

The result format is in the following example.

Example 1:
Input:

personId lastName firstName
1WangAllen
2AliceBob
Table: Person
addressId personId city state
12New York CityNew York
23LeetcodeCalifornia
Table: Address

Output:

firstName lastName city state
AllenWangNullNull
BobAliceNew York CityNew 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
Scroll to Top