SQL实现LeetCode(175.联合两表)

2022-05-15 0 157

[LeetCode] 175.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:

FirstName, LastName, City, State

LeetCode还出了是来到数据库的题,来那么也来做做吧,这道题是第一道,相对来说比较简单,是一道两表联合查找的问题,我们需要用到Join操作,关于一些Join操作可以看我之前的博客SQL Left Join, Right Join, Inner Join, and Natural Join 各种Join小结,最直接的方法就是用Left Join来做,根据PersonId这项来把两个表联合起来:

解法一:

SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address ON Person.PersonId = Address.PersonId;

在使用Left Join时,我们也可以使用关键Using来声明我们相用哪个列名来进行联合:

解法二:

SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address USING(PersonId);

或者我们可以加上Natural关键字,这样我们就不用声明具体的列,MySQL可以自行搜索相同的列:

解法三:

SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person NATURAL LEFT JOIN Address;

参考资料:

https://leetcode.com/discuss/21216/its-a-simple-question-of-left-join-my-solution-attached

https://leetcode.com/discuss/53001/comparative-solution-between-left-using-natural-left-join

到此这篇关于SQL实现LeetCode(175.联合两表)的文章就介绍到这了,更多相关SQL实现联合两表内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 MySql SQL实现LeetCode(175.联合两表) https://www.niceym.com/38465.html