LeetCode: 175. Combine Two Tables

Solution with step by step explanation

B M Mahmud
1 min readNov 25, 2023
Photo by Kevin Ku on Unsplash

Methods
Based on their same column personId, the Person and Address tables can be joined using an LEFT JOIN to fix this issue. This is how the question might appear:

# Write your MySQL query statement below
select firstname, lastname, city, state
from person
Left join Address on person.personId = Address.personId

Here, we select the firstName and lastName columns from the Person table, and the city and state columns from the Address table. We use a LEFT JOIN to combine the tables based on their personId columns. If a personId in the Person table doesn’t have a corresponding entry in the Address table, the city and state columns will be NULL. We then return the resulting table.

This query should produce the desired output:

+-----------+----------+---------------+----------+
| firstName | lastName | city | state |
+-----------+----------+---------------+----------+
| Allen | Wang | NULL | NULL |
| Bob | Alice | New York City | New York |
+-----------+----------+---------------+----------+

--

--

B M Mahmud

Hi, I am Mahmud. I love to share my ideas and learning strategies. You know, Sharing is caring. To know me more, check out my all links, bio.info/imash