学习记录:Leetcode175.组合两张表以及sql四种连接
175组合两张表
编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:
思路:本题为连接查询,有Person以及Adress两张表,地址信息存在Adress里面,也就是以Person表为主进行查询,可以使用left join或者right join;
sql:
select FirstName, LastName, City, State from Person as p
left join Address as a on p.PersonId = a.PersonId 或
select FirstName, LastName, City, State from Address as a
right join Person as p on a.PersonId = p.PersonId
拓展
sql的四种连接:左外连接(left join),右外连接(right join),内连接(inner join),全连接(full join)
- left join:连接查询时,以左表为主,返回左表所有行,即使右表匹配不上;
- right join:连接查询时,以右表为主,返回右表所有行,即使左表匹配不上;
- inner join:连接查询时,取并集,只保留两张表中完全匹配的行;
- full join:连接查询时,取交集,返回两表所有行,就算没有匹配;
个人学习笔记,不喜勿喷,欢迎交流!!!