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:
FirstName, LastName, City, State
本题主要考察sql中left join、right join、innner join的使用和其中的区别。
select Person.FirstName, Person.LastName, Address.City, Address.State
from Person
left join Address
on Person.PersonId=Address.PersonId;
SQL 连接:
1. INNER JOIN:如果表中有至少一个匹配,则返回行;
2. LEFT JOIN:即使右表中没有匹配,也从左表返回所有的行;
3. RIGHT JOIN:即使左表中没有匹配,也从右表返回所有的行