SQL Join語法圖示

這篇主要目的是介紹集合, 使用 SQL Join 指令時的語法與集合的關係, 資料可以參考這篇: http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

(以上圖片引用自: http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins )

在資料庫查詢時, 使用 Join 語法是用來查詢多個資料表間的相關資料狀況用的, 區分為 inner join 及 outer join 兩種, 不指定時預設為 inner join, 也就是在兩邊都存在的資料, 使用 inner join 查詢, 例如 select a.sid from table_a a inner join table_b b on a.sid=b.sid 時, 會出現同時在 a 與 b 的 sid 都存在的資料.

例如 table_a 存在 1, 2, 3, 5, 6, 7, 10, 11 共八筆資料, 而 table_b 存在 2, 3, 4, 5, 6, 7, 8 共七筆資料時, 使用 inner join 則取出 2, 3, 5, 6, 7 共五筆資料.

而 left join (也就是 left outer join), 則是取出以左邊為主, 不管右邊是否存在的資料, (不存在的資料會用 null 值補齊欄位), 如:

select a.sid from table_a a left join table_b b on a.sid=b.sid

則會取出 1, 2, 3, 4, 5, 7, 10 , 11 共八筆資料,

而 right join (也就是 right outer join), 則是取出以右邊為主, 不管左邊是否存在的資料, 如:

select a.sid from table_a a right join table_b b on a.sid=b.sid

則會取出 2, 3, 4, 5, 6, 7, 8 共七筆資料.

另外還有 full join (也就是 full outer join)則是兩邊都取出來, 如:

select a.sid, b.sid from table_a a full join table_b b on a.sid=b.sid

則會取出兩個表全部的內容, 1, 2, 3, 5, 6, 7, 10, 11, 4, 8 共十筆資料,

其他若是需要做其他的集合, 只需要再加上 where 中的 is null 就可以產生差集這樣的方式.

繼續閱讀:
http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
http://blog.wu-boy.com/2009/01/mysqlleft-right-inner-outer-join-%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *