1. 程式人生 > 實用技巧 >Leetcode-SQL習題

Leetcode-SQL習題

Leetcode-SQL

連結:https://leetcode-cn.com/problems/combine-two-tables/solution/zu-he-liang-ge-biao-by-leetcode/

習題來源:力扣(LeetCode)

175-組合兩個表-2021-01-09

表1:Person

列名 型別
PersonID int
FirstName varchar
LastName varchar

*** ----------------------

PresonID 是上表主鍵

表2:Address

列名 型別
AddressId int
PersonId int
City varchar
State varchar

*** ----------------------

AddressId 是上表主鍵

要求:編寫一個SQL查詢,滿足條件;無論person是否有地址資訊,都需要基於上述兩表提供person的以下資訊:

FirstName LastName City State
點選檢視
--我的答案
select
    FirstName,
    LastName,
    City,
    state
from
    (
        select
            PersonId,
            FirstName,
            LastName
        from
            Person
    ) a
    left join (
        select
            PersonId,
            City,
            State
        from
            Address
    ) b on a.PersonId = b.PersonId

--官方建議答案
select FirstName, LastName, City, State
from Person left join Address
on Person.PersonId = Address.PersonId