表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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combine-two-tables
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
一解
条件表示「无论 person 是否有地址信息,都表示 FirstName, LastName, City, State」,由此使用外键 outer join
进行连接,指向 Person 。
WHERE 与 ON 区别如下:
只有在外连接时不一样,数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户:
- ON 条件是在生成临时表时使用的条件,它不管 ON 中的条件是否为真,都会返回左边表(LEFT OUTER JOIN)中的记录。
- WHERE 条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有 LEFT OUTER JOIN 的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。
参考以下输入和输出:
// 输入
{"headers":{"Person":["PersonId","LastName","FirstName"],"Address":["AddressId","PersonId","City","State"]},"rows":{"Person":[[1,"Wang","Allen"],[2,"Alice","Bob"]],"Address":[[1,2,"New York City","New York"],[2,3,"Leetcode","California"]]}}
// 输出
{"headers": ["FirstName", "LastName", "City", "State"], "values": [["Allen", "Wang", null, null], ["Bob", "Alice", "New York City", "New York"]]}
SELECT FirstName, LastName, City, State FROM Person LEFT OUTER JOIN Address ON Person.PersonId = Address.PersonId