詳解Mysql兩表?join?查詢方式
更新時間:2022年10月23日 11:02:56 作者:LoveDR_1995
這篇文章主要介紹了Mysql兩表?join?查詢方式,主要包括SQL基本語法格式ji3種join方式,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
一、SQL基本語法格式
SELECT DISTINCT < select_list > FROM < left_table > < join_type > JOIN < right_table > ON <join_condition> WHERE < where_condition > GROUP BY < group_by_list > HAVING < having_condition > ORDER BY < order_by_condition > LIMIT < limit_number >
二、3種join方式
1. left join(左連接)
A left join B 得到A表的所有字段,如果沒有匹配到連接條件則用null填充
select A.*,B.* from A left join B on A.id = B.id;
2. right join(右連接)
A right join B 得到B表所有的字段
select A.*,B.* from A right join B on A.id=B.id;
3. inner join(內連接)
A inner join B得到(A和B的交集)
select A.*,B.* from A inner join B on A.id=B.id;
4. 在理解上面的三種join下,查詢(A - A∩B)
select A.*,B.* from A left join B on A.id=B.id where B.id is null;
5. 查詢 ( B - A∩B )
select A.*,B.* from A right join B on A.id=B.id where A.id is null;
6. 查詢(A∪B - A∩B)
利用union去重將上面的第四、第五種兩條sql中間用union連接即可完成;即先完成一小部分的,然后將兩個拼起來的思想。
select A.*,B.* from A left join B on A.id=B.id where B.id is null union select A.*,B.* from A right join B on A.id=B.id where A.id is null;
7. 查詢 AUB
MySQL中求并集可以使用union關鍵字進行處理(自動去重)
select A.*,B.* from A left join B on A.id=B.id UNION select A.*,B.* from A right join B on A.id=B.id;
到此這篇關于Mysql兩表 join 查詢方式的文章就介紹到這了,更多相關Mysql join 查詢內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MySql創(chuàng)建帶解釋的表及給表和字段加注釋的實現(xiàn)代碼
這篇文章主要介紹了MySql創(chuàng)建帶解釋的表以及給表和字段加注釋的實現(xiàn)方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12