Combine Two Tables Problem


Description

LeetCode Problem 175.

Table: Person

1
2
3
4
5
6
7
8
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
PersonId is the primary key column for this table.

Table: Address

1
2
3
4
5
6
7
8
9
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+
AddressId is the primary key column for this table.

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

1
FirstName, LastName, City, State


MySQL Solution

We can join the two tables to get the address information of a person. Considering there might not be an address information for every person, we should use outer join instead of the default inner join.

1
2
3
select Person.FirstName, Person.LastName, Address.City, Address.State
from Person
left join Address on Person.PersonId = Address.PersonId;




Related Posts

Nth Highest Salary Problem

LeetCode 177. Write a SQL query to get the nth...

Rank Scores Problem

LeetCode 178. Write a SQL query to rank scores. If...

Consecutive Numbers Problem

LeetCode 180. Write an SQL query to find all numbers...

Second Highest Salary Problem

LeetCode 176. Given the Employee table, write a SQL query...

Employees Earning More Than Their Managers Problem

LeetCode 181. Given the Employee table, write a SQL query...

Combine Two Tables Problem

LeetCode 175. Write a SQL query for a report that...