Combine Two Tables LeetCode Solution

This Leetcode problem Combine Two Tables LeetCode Solution is done in SQL.

List of all LeetCode Solution

Combine Two Tables LeetCode Solution

Combine Two Tables LeetCode Solution

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
1Wang Allen
2Alice Bob
Table: Person
addressId personId city state
12New York CityNew York
23Leetcode California
Table: Address

Output:

firstName lastName city state
Allen Wang Null Null
Bob Alice New 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.

Combine Two Tables LeetCode Solution MySQL

select 
  FirstName, 
  LastName, 
  City, 
  State 
from 
  Person as p 
  left join 
  Address as a 
  on 
  p.PersonId = a.PersonId;Code language: SQL (Structured Query Language) (sql)

Combine Two Tables LeetCode Solution 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 resultCode language: JavaScript (javascript)
Scroll to Top