今天來介紹JOIN,有以下幾個模式!
- JOIN
- LEFT JOIN
- RIGHT JOIN
- FULL OUTER JOIN
- CROSS JOIN
SELECT aga.area_pkid, a.name, aga.subid, aga.place, aga.kind
FROM adoption_gov_animals AS aga LEFT JOIN areas AS a
ON aga.area_pkid = a.id;
解釋SQL
複習一下 aga.area_pkid
以這個欄位的撰寫方式,aga 是 adoption_gov_animals 的縮寫,在第二行中 adoption_gov_animals AS aga
AS 關鍵字可以設定一個名稱來代表adoption_gov_animals 這張資料表
以上方查詢的程式碼來看的話是使用 LEFT JOIN
關鍵字,左右兩邊都有一張表!為了好辨識我們改成這樣。
FROM left_table LEFT JOIN right_table
所以我們現在就有 left_table
左邊資料表以及右邊資料表 right_table
,等等就會以這個名詞來做講解。
第三行 ON
關鍵字告訴資料庫! 兩張表對應方式的邏輯。

JOIN
JOIN 關鍵字 左邊(left_table) 以及 右邊 (right_table)有對應到數值才顯示!就是一個數學集合的概念。

LEFT JOIN
以左邊為主,左邊(left_table)資料全部列出來,去對應右邊的資料表(right_table) 有對到顯示,沒有對應的值顯示 null 表示空值

RIGHT JOIN
就是與LEFT JOIN 相反,以右邊的資料表(right_table) 全部列出來,不管左邊的資料表(left_table)有沒有對應值

FULL OUTER JOIN
還是左邊先,左邊資料表全部查詢出來有對應到顯示對應值,沒有對到的顯示空值,如果右邊的資料表,有沒有對應到的內容,全部也一起顯示出來,左邊的表顯示空值。

CROSS JOIN
把左邊的資料表與右邊資料表的每一個值做匹配,呈現出所有可能的排列組合。因為不考慮是否有無匹配,所以不需要 ON關鍵字。

加入篩選
因為對應不到的值會填入 null 空值,這個值比較特別,代表這個欄位內容是空的,不是 "" 空字串,也不是數字0的意思。
我們可以用 WHERE left_table.cloumn IS NULL
來塞選出左邊來為顯示出來是null的結果。如果要找不為null的資料 使用 IS NOT NULL 即可。 不只可以運用在這邊。一般的資料表也可以這麼做篩選。
以 LEFT JOIN
查詢結果為例

可以下 WHERE right_table.名稱 IS NULL
就會出現根 JOIN 一樣的結果

結合更多資料表
上面都是以左右兩個資料表為範例,不過JOIN 是可以接很多個的喔!