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.
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.statefrom person pleft join Address a on a.personId = p.personId
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']]
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.