表连接与子查询

175. 组合两个表

表1: Person

+-------------+---------+
| 列名         | 类型     |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
PersonId 是上表主键

表2: Address

+-------------+---------+
| 列名         | 类型    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+
AddressId 是上表主键

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

FirstName, LastName, City, State
# 表连接
select FirstName,LastName,City,State from Person left join Address on Person.PersonId=Address.PersonId
# 子查询
select 
FirstName,
LastName,
(select City from Address where Address.PersonId = Person.PersonId) as City,
(select State from Address where Address.PersonId = Person.PersonId) as State
from Person 

连接

  • A inner join B 取交集。
  • A left join B 取 A 全部,B 没有对应的值为 null。
  • A right join B 取 B 全部 A 没有对应的值为 null。
  • A full outer join B 取并集,彼此没有对应的值为 null。
  • 对应条件在 on 后面填写

子查询

  • 子查询会产生临时表,在查询结束后自动删除
  • 子查询会多次遍历表

重点(待解决):连接 和 子查询 的效率???

posted @ 2021-05-22 09:33  Manan_vision  阅读(134)  评论(0)    收藏  举报