1.首先准備兩張表
部門表:
員工表:
以下我們就對這兩張表進行不同的連接操作
1.內連接
作用: 查詢兩張表的共有部分
語句:Select <select_list> from tableA A Inner join tableB B on A.Key = B.Key
示例:SELECT * from employee e INNER JOIN department d on e.dep_id = d.id;
結果顯示:通過這個查找的方法,我們沒有查到id為8的數據
2.左連接
作用:把左邊表的內容全部查出,右邊表只查出滿足條件的記錄
語句:Select <select_list> from tableA A Left Join tableB B on A.Key = B.Key
示例:SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id;
結果顯示:
3.右連接
作用:把右邊表的內容全部查出,左邊表只查出滿足條件的記錄
語句:Select <select_list> from tableA A Left Join tableB B on A.Key = B.Key
示例:SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id;
結果顯示:
4.查詢左表獨有數據
作用:查詢A的獨有數據
語句:Select <select_list> from tableA A Left Join tableB B on A.Key = B.Key where B.key IS NULL
示例:SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id WHERE d.id IS NULL;
結果顯示:
5.查詢右表獨有數據
作用:查詢B的獨有數據
語句:Select <select_list> from tableA A Right Join tableB B on A.Key = B.Key where A.key IS NULL
示例:SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id WHERE e.id IS NULL;
結果顯示:
6.全連接
作用:查詢兩個表的全部信息
語句:Select <select_list> from tableA A Full Outter Join tableB B on A.Key = B.Key
注:Mysql 默認不支持此種寫法 Oracle支持 可以使用將左連接與右連接結合起來作為全連接
示例:
SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id
UNION
SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id
結果顯示:
7.查詢左右表各自的獨有的數據
作用:查詢A和B各自的獨有的數據
語句:Select <select_list> from tableA A Full Outter Join tableB B on A.Key = B.Key where A.key = null or B.key=null
示例:
SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id WHERE d.id is NULL
UNION
SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id WHERE e.dep_id is NULL
結果顯示: