Mysql中常用的幾種join連接方式總結(jié)
1.首先準備兩張表
部門表:
員工表:
以下我們就對這兩張表進行不同的連接操作
1.內(nèi)連接
作用: 查詢兩張表的共有部分
語句:Select 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;
結(jié)果顯示:通過這個查找的方法,我們沒有查到id為8的數(shù)據(jù)
2.左連接
作用:把左邊表的內(nèi)容全部查出,右邊表只查出滿足條件的記錄
語句:Select 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;
結(jié)果顯示:
3.右連接
作用:把右邊表的內(nèi)容全部查出,左邊表只查出滿足條件的記錄
語句:Select 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;
結(jié)果顯示:
4.查詢左表獨有數(shù)據(jù)
作用:查詢A的獨有數(shù)據(jù)
語句:Select 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;
結(jié)果顯示:
5.查詢右表獨有數(shù)據(jù)
作用:查詢B的獨有數(shù)據(jù)
語句:Select 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;
結(jié)果顯示:
6.全連接
作用:查詢兩個表的全部信息
語句:Select from tableA A Full Outter Join tableB B on A.Key = B.Key
注:Mysql 默認不支持此種寫法 Oracle支持 可以使用將左連接與右連接結(jié)合起來作為全連接
示例:
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
結(jié)果顯示:
7.查詢左右表各自的獨有的數(shù)據(jù)
作用:查詢A和B各自的獨有的數(shù)據(jù)
語句:Select 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
結(jié)果顯示:
總結(jié)
到此這篇關(guān)于Mysql中常用的幾種join連接方式的文章就介紹到這了,更多相關(guān)Mysql join連接方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL數(shù)據(jù)庫聚合函數(shù)與分組查詢舉例詳解
在MySQL中聚合函數(shù)和分組查詢經(jīng)常一起使用,下面這篇文章主要給大家介紹了關(guān)于MySQL數(shù)據(jù)庫聚合函數(shù)與分組查詢的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-01-01CentOS7環(huán)境下MySQL8常用命令小結(jié)
在進行MySQL的優(yōu)化之前必須要了解的就是MySQL的查詢過程,下面這篇文章主要給大家介紹了關(guān)于CentOS7環(huán)境下MySQL8常用命令的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-06-06麒麟系統(tǒng)上安裝?MySQL?8.0.24的詳細步驟(避坑指南)
這篇文章主要介紹了麒麟系統(tǒng)上安裝MySQL8.0.24的詳細步驟,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08mysql 數(shù)據(jù)庫安裝經(jīng)驗問題匯總
這篇文章主要介紹了mysql 數(shù)據(jù)庫安裝經(jīng)驗問題匯總,本文介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2016-09-09