Skip to content →

[MySQL] 表格連接JOIN和UNION

之前在搜尋二個資料表(Table)時,都會用下面的寫法:

這次需要搜尋三個資料表,用之前的寫法怎麼樣都出現問題><
只好拜託谷歌大神幫忙,
才發現原來還有另一種寫法,問題就順利解決了^o^



順便介紹一下表格連接的用法:
JOIN 分 INNER JOIN 和 OUTER JOIN(又分 LEFT、RIGHT)



INNER JOIN:
  select A.month ,B.month from A INNER JOIN B on A.month=B.month
  得到 Apr , May

LEFT OUTER JOIN:
  select A.month ,B.month from A LEFT OUTER JOIN B on A.month=B.month
  得到 Jan ,Feb ,Mar ,Apr ,May

RIGHT OUTER JOIN:
  select A.month ,B.month from A RIGHT OUTER JOIN B on A.month=B.month
  得到 Apr , May ,Jun

UNION :
  select month from A UNION select month from B
  得到 Jan ,Feb ,Mar ,Apr ,May ,Jun
  用法有些規定:搜尋的欄位數要相同,回傳的欄位型態也要相同。

Published in MySQL

Comments are closed.