LeetCode--Database--175. Combine Two Tables

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/meteorsshower2013/article/details/82251530

题目:

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

猜你喜欢

转载自blog.csdn.net/meteorsshower2013/article/details/82251530