LeetCode 175. Combine Two Tables (SQL語句中on和where的區別)

Description:

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

Solution:

這裏要使用左結合,無論右邊表是否有數據都返回。
口訣:先執行 on,後執行 where;on 是建立關聯關係,where 是對關聯關係的篩選。
這裏用 on :

  1. on條件是在生成臨時表時使用的條件,它不管on中的條件是否爲真,都會返回左邊表中的記錄,還會返回on條件爲真的記錄
    2.where條件是在臨時表生成好後,再對臨時表進行過濾的條件。這時已經沒有left join的含義(必須返回左邊表的記錄)了,條件不爲真的就全部過濾掉。
select FirstName, LastName, City, State from Person
left join Address
on Person.PersonId = Address.PersonId;

References/參考:https://www.cnblogs.com/july-sunny/p/12500542.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章