|
| 1 | +-- Table: Person |
| 2 | +-- |
| 3 | +-- +-------------+---------+ |
| 4 | +-- | Column Name | Type | |
| 5 | +-- +-------------+---------+ |
| 6 | +-- | personId | int | |
| 7 | +-- | lastName | varchar | |
| 8 | +-- | firstName | varchar | |
| 9 | +-- +-------------+---------+ |
| 10 | +-- personId is the primary key column for this table. |
| 11 | +-- This table contains information about the ID of some persons and their first and last names. |
| 12 | +-- |
| 13 | +-- Table: Address |
| 14 | +-- |
| 15 | +-- +-------------+---------+ |
| 16 | +-- | Column Name | Type | |
| 17 | +-- +-------------+---------+ |
| 18 | +-- | addressId | int | |
| 19 | +-- | personId | int | |
| 20 | +-- | city | varchar | |
| 21 | +-- | state | varchar | |
| 22 | +-- +-------------+---------+ |
| 23 | +-- addressId is the primary key column for this table. |
| 24 | +-- Each row of this table contains information about the city and state of one person with ID = PersonId. |
| 25 | +-- |
| 26 | +-- Write an SQL query 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. |
| 27 | +-- Return the result table in any order. |
| 28 | +-- The query result format is in the following example. |
| 29 | +-- |
| 30 | +-- Example 1: |
| 31 | +-- |
| 32 | +-- Input: |
| 33 | +-- Person table: |
| 34 | +-- +----------+----------+-----------+ |
| 35 | +-- | personId | lastName | firstName | |
| 36 | +-- +----------+----------+-----------+ |
| 37 | +-- | 1 | Wang | Allen | |
| 38 | +-- | 2 | Alice | Bob | |
| 39 | +-- +----------+----------+-----------+ |
| 40 | +-- Address table: |
| 41 | +-- +-----------+----------+---------------+------------+ |
| 42 | +-- | addressId | personId | city | state | |
| 43 | +-- +-----------+----------+---------------+------------+ |
| 44 | +-- | 1 | 2 | New York City | New York | |
| 45 | +-- | 2 | 3 | Leetcode | California | |
| 46 | +-- +-----------+----------+---------------+------------+ |
| 47 | +-- Output: |
| 48 | +-- +-----------+----------+---------------+----------+ |
| 49 | +-- | firstName | lastName | city | state | |
| 50 | +-- +-----------+----------+---------------+----------+ |
| 51 | +-- | Allen | Wang | Null | Null | |
| 52 | +-- | Bob | Alice | New York City | New York | |
| 53 | +-- +-----------+----------+---------------+----------+ |
| 54 | +-- Explanation: |
| 55 | +-- There is no address in the address table for the personId = 1 so we return null in their city and state. |
| 56 | +-- addressId = 1 contains information about the address of personId = 2. |
| 57 | + |
| 58 | +SELECT Person.FirstName, Person.LastName, Address.City, Address.State |
| 59 | +FROM Person |
| 60 | + LEFT JOIN Address |
| 61 | + ON Person.PersonId = Address.PersonId; |
0 commit comments