leetcode--175--组合两个表

2020-03-28  本文已影响0人  minningl

题目:
表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

链接:https://leetcode-cn.com/problems/combine-two-tables

思路:这是一道sql题,主要是考察left join的用法

sql如下:

# Write your MySQL query statement below
select FirstName,
       LastName,
       City,
       State
  from (
        select PersonId,
               FirstName,
               LastName
          from Person
       )a
 left join(
        select AddressId,
               PersonId,
               City,
               State
          from Address
       )b
    on a.PersonId=b.PersonId

简化后:

# Write your MySQL query statement below
select 
  Person.FirstName, 
  Person.LastName, 
  Address.City, 
  Address.State 
from 
  Person 
  left join Address 
  on Person.PersonId = Address.PersonId
上一篇下一篇

猜你喜欢

热点阅读