美文网首页
leetcode--175--组合两个表

leetcode--175--组合两个表

作者: minningl | 来源:发表于2020-03-28 15:30 被阅读0次

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

    相关文章

      网友评论

          本文标题:leetcode--175--组合两个表

          本文链接:https://www.haomeiwen.com/subject/mmxsuhtx.html