This Leetcode problem Combine Two Tables LeetCode Solution is done in SQL.
List of all LeetCode Solution
![Combine Two Tables LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Combine Two Tables LeetCode Solution
Table of Contents
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.
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 result
Code language: JavaScript (javascript)