LeetCode 175 – Combine Two Tables (SQL & Python) Solutions

This article is going to provide the solution to LeetCode 175. It’s an easy difficulty question.

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.

LeetCode Question Link

If you want to skip the article, check out the full YouTube video where I code the answer live.

LeetCode 175 SQL Solution

select
    p.firstName,
    p.lastName,
    a.city,
    a.state
from person p
left join Address a on a.personId = p.personId
This SQL code is a SELECT query that retrieves data from two tables, person and Address, using a LEFT JOIN operation. Here’s a breakdown:

p.firstName and p.lastName are columns from the person table, representing the first name and last name of individuals. a.city and a.state are columns from the Address table, representing the city and state information.

FROM person p indicates that data is being retrieved from the person table and aliased as p.

LEFT JOIN Address a ON a.personId = p.personId performs a LEFT JOIN operation between the person table (p) and the Address table (a) based on the common column personId.

The LEFT JOIN ensures that all records from the person table are included in the result set, regardless of whether there is a matching record in the Address table.

ON a.personId = p.personId specifies the join condition, where the personId column in the Address table matches the personId column in the person table.

LeetCode 175 Python Solution

import pandas as pd
def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFrame:
    final = person.merge(address, on='personId', how='left')
    return final[['firstName', 'lastName', 'city', 'state']]
The leetcode question starts with a function named combine_two_tables that takes two parameters: person and address, both expected to be pandas DataFrames.

This first line of the function merges the two DataFrames (person and address) based on the column ‘personId’ using a left join.

The how=’left’ parameter specifies that all rows from the person DataFrame will be included in the final DataFrame, regardless of whether there is a matching ‘personId’ in the address DataFrame.

This final line returns a new DataFrame containing only the columns ‘firstName’, ‘lastName’, ‘city’, and ‘state’ from the merged DataFrame (final).

Leave a Reply

Your email address will not be published. Required fields are marked *