如何在MySQL 進行一個聯合查詢

參考文章:

https://www.jianshu.com/p/95c170ab5513

https://blog.csdn.net/weixin_39411321/article/details/90602030

 MySQL除了普通的增刪改查的sql 用的多以外,像多表查詢其實在項目裏用的是非常多的,下面就隨着小編一起看下去吧

1) 知識體系 

 

 

2)表

 我這邊準備了倆張表show_column 和user_coulmn ,show_column的id 和 user_column的 column_id 關聯 ,user_column的uid 和bos_user的user_id 關聯, 目前bos_user 這張表與下文演示無關。

 

3)內連接 

顯式內連接

 主要原理是根據關聯條件,從左表中查詢每一條記錄 去右表中的所有記錄進行匹配,如果不滿足關聯條件,則數據查詢不出來。

-- 1.顯式內連接
-- 語法:select table1.*,table2.* from table1 inner join table2 on 關聯條件
select a.* ,b.* from show_column a inner join user_column b on a.id= b.column_id where a.is_del='0';

 

隱式內連接

-- 2.隱式內連接
-- 語法: select table1.*,table2.*  from table1,table2 where 關聯條件
select a.*,b.* from show_column a,user_column b where a.id = b.column_id;

 

 

 

4)外連接

左外連接【left join】

 以left 左邊的表爲主,查詢出裏面所有記錄,根據關聯條件查詢右邊表的數據,能匹配的正確保留,不能匹配的其他字段裏面的值爲null

-- 3.左外連接
-- 語法: select table1.*,table2.* from table1 a,
select a.page,a.field_name,a.id,b.* from show_column a left join user_column b on a.id = b.column_id

 

右外連接[right join]

原理: 查詢出right 右邊表的所有數據,根據關聯條件查詢 right 右邊的數據,能夠匹配的將數據查詢出來,不能匹配的將數據設置爲null. 

-- 4.右外連接
select a.*,b.* from show_column a right join user_column b on a.id = b.column_id

 

 

 

5) 子查詢

-- 5. 子查詢
select a.*  from show_column a where id in(select column_id from user_column );

 

6) 補充一個聯合查詢

union 關鍵字 ,union 代表查詢倆張表去除重複後的數據,按照默認排序,union all 代表查詢倆張表全部數據,且沒有順序

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章