---
title: 【LeetCode】0175. Combine Two Tables
date: 2018-12-19
is_modified: false
disqus: cynthiahackmd
categories:
- "面試刷題"
tags:
- "LeetCode"
- "SQL"
- "Left Join"
---
{%hackmd @CynthiaChuang/Github-Page-Theme %}
<br>
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:
`FirstName, LastName, City, State`
<!--more-->
<br>
Table: `Person`
| Column Name | Type |
|----------------- |--------- |
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
PersonId is the primary key column for this table.
<br>
Table: `Address`
| Column Name | Type |
|----------------- |--------- |
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
AddressId is the primary key column for this table.
## 解題邏輯與實作
原來 LeetCode 還有出資料庫的題目阿,不過題目看來不多,而且題目也不太難,所以手癢稍微試了一下。
### Left Join
這題看起來就是聯合查表的題目,檢查一下兩張 Table 的欄位,發現 **PersonId** 這欄位兩張表都有且命名也相同,所以我選它直接使用 **Using** 來進行聯合。
```sql
SELECT p.FirstName, p.LastName, a.City, a.State
FROM Person p LEFT OUTER JOIN Address a USING (PersonId);
```
## 其他連結
1. [【LeetCode】0000. 解題目錄](/x62skqpKStKMxRepJ6iqQQ)
<br><br>
> **本文作者**: 辛西亞.Cynthia
> **本文連結**: [辛西亞的技能樹](https://cynthiachuang.github.io/LeetCode-0175-Combine-Two-Tables) / [hackmd 版本](https://hackmd.io/@CynthiaChuang/LeetCode-0175-Combine-Two-Tables)
> **版權聲明**: 部落格中所有文章,均採用 [姓名標示-非商業性-相同方式分享 4.0 國際](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!