題目:
Table:Person
Column Name | Type |
---|---|
PersonId | int |
FirstName | varchar |
LastName | varchar |
PeronId is the primary key column for this table.
Table:ddress
Column | 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 int the Person table,regardless if there is an address for each of those people
FirstName,LastName,City,State
解答一
select Person.FirstName,Person.LastName,Address.City,Address.State from Person,Address where Person.PersonId = Address.PersonId
錯誤答案
題目要求是遍歷person表中每一個人,這個人可以沒有address信息,所以這個地方有問題,因爲where Person.Id = address.PersonId 可以爲false】
查閱左右連接知識
下面列出了您可以使用的 JOIN 類型,以及它們之間的差異。
JOIN: 如果表中有至少一個匹配,則返回行
LEFT JOIN: 即使右表中沒有匹配,也從左表返回所有的行
RIGHT JOIN: 即使左表中沒有匹配,也從右表返回所有的行
FULL JOIN: 只要其中一個表中存在匹配,就返回行
解答二,使用left join
select Person.FirstName,Person.LastName,Address.City,Address.State from Person left join Address on Person.PersonId = Address.PersonId
解答三,使用right join
select Person.FirstName,Person.LastName,Address.City,Address.State from Address right join Person on Person.PersonId = Address.PersonId