欢迎来到代码驿站!

Mysql

当前位置:首页 > 数据库 > Mysql

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

时间:2022-12-26 10:52:02|栏目:Mysql|点击:

[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

上一篇:mysql中int(3)和int(10)的数值范围是否相同

栏    目:Mysql

下一篇:mysql日志文件之undo log和redo log

本文标题:SQL实现LeetCode(175.联合两表)

本文地址:http://www.codeinn.net/misctech/222205.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有