1. 程式人生 > >【LeetCode刷題】SQL-Combine Two Tables

【LeetCode刷題】SQL-Combine Two Tables

介紹 左關聯查詢 col 每一個 cit http sid combine sql查詢

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
PersonId is the primary key column for this table.

Table: Address

+-------------+---------+
| 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:

題目大意:

有兩個數據表:Person表和Address表。Person(人員)表主鍵為PersonId,Address(地址)表主鍵是AddressId,通過PersonId與Person表關聯。

編寫一個SQL查詢,對於Person表中的每一個人,取出FirstName, LastName, City, State屬性,無論其地址信息是否存在。

解題思路:

本題是一個簡單的連表查詢,以Person表為主表,Address表為副表。所以可以使用左關聯查詢來進行聯表查詢。

關於左(外)關聯、右(外)關聯、內關聯以及外關聯查詢。詳見此篇博客:http://www.cnblogs.com/afirefly/archive/2010/10/08/1845906.html

一句話介紹就是:左關聯(Left Join)就是以左邊的表為準,只要左邊的表有數據就輸出,不管右邊的表有沒有數據。右關聯(Right Join)相反,以右邊的表為準。而內關聯則是兩張表都要有數據才能查詢到。外關聯則是只要任意一張表有數據就能查詢並顯示。

所以本題使用左關聯。

SQL語句:

SELECT p.FirstName, p.LastName, a.City, a.State
FROM Person p LEFT JOIN Address a on a.PersonId=p.PersonId;

【LeetCode刷題】SQL-Combine Two Tables