SQL实现LeetCode(175.联合两表)
[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;
解法二:
SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address USING(PersonId);
解法三:
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系列多表连接查询92及99语法示例详解教程
- Linux下MYSQL 5.7 找回root密码的问题(亲测可用)
- MySQL 什么时候使用INNER JOIN 或 LEFT JOIN
- Android(安卓)-- Android(安卓)JUint 与 Sqlite
- android中SqLite query中用selectionArgs处理字符传值
- android从服务器下载文件(php+apache+win7+MySql)
- Android(安卓)ORM SQL Top 5
- android SQLiteDatebase 实践
- Android(安卓)SQLiteDatabase的使用