sql的四種連接——左外連接、右外連接、內連接、全連接


一、內連接

  滿足條件的記錄才會出現在結果集中。

 

二、 左外連接(left outer join,outer可省略)

左表全部出現在結果集中,若右表無對應記錄,則相應字段為NULL

 

 

舉例說明:

客戶表:
在這里插入圖片描述

訂單表:
在這里插入圖片描述

左外連接(LEFT OUTER JOIN)
  select first_name, last_name, order_date, order_amount

  from customers c

  left join orders o

  on c.customer_id = o.customer_id

  結果:右表(order)只選取customer_id在左表出現過的結果(符合條件的order_date, order_amount,所以最后兩行中date和amount都有NULL值)

 

 

三、右外連接(right outer join,outer可省略)

  右表全部出現在結果集中,若左表無對應記錄,則相應字段為NULL

 

 

舉例說明:

  select first_name, last_name, order_date, order_amount

  from customers c

  right join orders o

  on c.customer_id = o.customer_id

  結果:左表(customer)只選取customer_id在右表出現過的結果(符合條件的first_name和last_name,所以最后兩行中first_name和last_name都有NULL值)
在這里插入圖片描述

 

四、全連接(full outer join,outer可省略)

  全外連接=左外連接+右外連接

 

舉例:

  select first_name, last_name, order_date, order_amount

  from customers c

  full join orders o

  on c.customer_id = o.customer_id

結果:(左邊有右邊沒有,和右邊有左邊沒有的地方有NULL值)

 

 

參考:

https://www.pianshen.com/article/7828135881/

https://www.cnblogs.com/yyjie/p/7788413.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM