175.组合两个表

SQL架构:

1
2
3
4
5
6
Create table Person (PersonId int, FirstName varchar(255), LastName varchar(255))
Create table Address (AddressId int, PersonId int, City varchar(255), State varchar(255))
Truncate table Person
insert into Person (PersonId, LastName, FirstName) values ('1', 'Wang', 'Allen')
Truncate table Address
insert into Address (AddressId, PersonId, City, State) values ('1', '2', 'New York City', 'New York')

表1: Person:

1
2
3
4
5
6
7
+
| 列名 | 类型 |
+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
+

PersonId 是上表主键

表2: Address:

1
2
3
4
5
6
7
8
+
| 列名 | 类型 |
+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
+

AddressId 是上表主键

编写一个 SQL 查询,满足条件:
无论 person 是否有地址信息,都需要基于两表提供 person 的以下信息:

1
FirstName, LastName, City, State

思路:

查询目标:Person表的FirstName, LastName, City, State
查询范围:Person和Address

解答:

1
2
3
4
Select
Person.FirstName, Person.LastName, Address.City, Address.State
from
Person LEFT JOIN Address ON Person.PersonId = Address.PersonId;