【LeetCode刷题】SQL-Combine Two Tables

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;

转载于:https://www.cnblogs.com/contixue/p/7051213.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值