When working with relational databases, a common task is to combine data from multiple tables. This concept is illustrated well in the LeetCode problem "Combine Two Tables". In this post, we will explore how to approach this problem using SQL.
Problem Overview
The problem presents us with two tables:
Person Table: Contains personId (primary key), lastName, and firstName.
Address Table: Contains addressId (primary key), personId, city, and state.
Our objective is to write an SQL query that returns the first name, last name, city, and state of each person in the Person table. If a person does not have an address listed in the Address table, we should return null for their city and state.
Understanding the Data Structure
Here are the given tables with sample data:
Person Table
personId | lastName | firstName |
---|---|---|
1 | Wang | Allen |
2 | Alice | Bob |
Address Table
addressId | personId | city | state |
---|---|---|---|
1 | 2 | New York City | New York |
2 | 3 | Leetcode | California |
SQL Query Solution Approach
MySQL Solution
SELECT
p.firstName,
p.lastName,
a.city,
a.state
FROM
Person p
LEFT JOIN
Address a ON p.personId = a.personId;
PostgreSQL Solution
-- Write your PostgreSQL query statement below
SELECT
p.firstName,
p.lastName,
a.city,
a.state
FROM
Person p
LEFT JOIN
Address a ON p.personId = a.personId;
Oracle Solution
/* Write your PL/SQL query statement below */
SELECT
p.firstName,
p.lastName,
a.city,
a.state
FROM
Person p
LEFT JOIN
Address a ON p.personId = a.personId;
Comments
Post a Comment