↓Skip to main content
  1. LeetCode/

LeetCode 175: Combine Two Tables

·1 min· ·
LeetCode Easy Database
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2021-10-09

  • Submissions: Runtime Error → Accepted ×3

Approach
#

Everyone must appear even without a row in Address, so use Person LEFT JOIN Address (SQL Template 3): every left row is kept and unmatched right columns become NULL. An INNER JOIN would drop people without addresses.

My Attempts
#

Attempt 1 wrapped the join in parentheses with an alias as ouptut, which MySQL rejected (RE); dropping the alias passed.

Solution
#

SELECT p.firstName, p.lastName, a.city, a.state
FROM Person p
LEFT JOIN Address a ON p.personId = a.personId;

Complexity
#

Joining on personId, roughly O(n + m) with an index.

Mistakes to Avoid
#

  • To keep every left row use LEFT JOIN, not JOIN.
  • Wrapping a join in parentheses with an alias makes it a derived table; the syntax must be right.

Interview Explanation
#

People without an address must still appear, so I use Person LEFT JOIN Address, which leaves city and state NULL when there is no match.

Related

LeetCode 181: Employees Earning More Than Their Managers
·1 min
LeetCode Easy Database
LeetCode 181 note: self-join Employee on managerId = id to pair employees with managers, then compare salaries
LeetCode 182: Duplicate Emails
·1 min
LeetCode Easy Database
LeetCode 182 note: group by email and keep groups with HAVING COUNT(*) > 1
LeetCode 183: Customers Who Never Order
·1 min
LeetCode Easy Database
LeetCode 183 note: LEFT JOIN Orders, and customers with no matching order (o.id IS NULL) never ordered; NOT IN also works
LeetCode 196: Delete Duplicate Emails
·2 mins
LeetCode Easy Database
LeetCode 196 note: it must be a DELETE, not a SELECT; keep only the smallest id per email and delete the rest
LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length