mysql中各種join連表查詢總結
通常我們需要連線多個表查詢資料,以獲取想要的結果。
一、連線可以分為三類:
(1) 內連線:join,inner join
(2) 外連線:left join,left outer join,right join,right outer join,union,union all
(3) 交叉連線:cross join
二、準備需要演示的表:
CREATE TABLE `a` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', `a_name` varchar(32) DEFAULT '' COMMENT 'a表名稱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `b` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', `a_id` int(11) DEFAULT '0' COMMENT 'a表ID', `b_name` varchar(32) DEFAULT '' COMMENT 'b表名稱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
a表與b表的資料如圖中所示:
三、內連線inner join或join
select * from a inner join b on a.id = b.a_id; select * from a join b on a.id = b.a_id; select * from a, b where a.id = b.a_id;
結果如下:
內連線可以理解為,兩個表中同時滿足某條件的資料記錄組合。也就是表A和表B中滿足條件a.id = b.a_id的所有記錄。
當表A中的一條記錄對應表B中的多條記錄時,會以重複的方式對應多條表B記錄出現在結果集中。
當表B中的一條記錄對應表A中的多條記錄時,會以重複的方式對應多條表A記錄出現在結果集中。
四、外連線left join或right join
(1) 左外連線
select * from a left join b on a.id = b.a_id; select * from a left outer join b on a.id = b.a_id;
左外連線,會以左邊的表A為主表,返回所有行,即使右表B中沒有匹配的行。
如果左邊的表A在右表B中找不到一條記錄,則返回表A所有記錄並且表B相應的欄位設為null。
如果左邊的表A在右表B中找到多條記錄,則以相同表A記錄和不同表B記錄多條顯示在結果集中。
這種情況下,其實是把表A中所有記錄都查詢出來了,包括不滿足條件的記錄。
如果我們只想查出表A中滿足條件的,或是不滿足條件的,該怎麼查?
select * from a left join b on a.id = b.a_id where b.a_id is not null; select * from a left outer join b on a.id = b.a_id where b.a_id is not null;
上面的語句查詢的,就是表A中滿足條件的。
select * from a left join b on a.id = b.a_id where b.a_id is null; select * from a left outer join b on a.id = b.a_id where b.a_id is null;
上面的語句查詢的,就是表A中不滿足條件的。
(2) 右外連線
select * from a right join b on a.id = b.a_id; select * from a right outer join b on a.id = b.a_id;
右外連線其實跟左外連線一樣,區別在於 主表的確定,兩者之間可以相互轉換。
右外連線的描述基本與左外連線相同,這裡就不過多描述了。
(3) 全連線full join
mysql並不支援全連線,不過有相應的替代方案,就是left join union right join 來代替。
select * from a left join b on a.id = b.a_id union select * from a right join b on a.id = b.a_id;
全連線會從表A和表B中返回所有的行,如果表A中的行在表B中沒有匹配,或是表B中的行在表A中沒有匹配,這些行都會顯示,不存在的欄位以null補充。
union會把其中重複的行合併。
這種情況下,是把表A和表B中滿足條件和不滿足條件的記錄都顯示出來了。
如果只想顯示所有不滿足條件的記錄,則通過如下語句:
select * from a left join b on a.id = b.a_id where b.a_id is null union select * from a right join b on a.id = b.a_id where a.id is null;
如果只想顯示所有滿足條件的記錄,則通過如下語句:
select * from a left join b on a.id = b.a_id where b.a_id is not null union select * from a right join b on a.id = b.a_id where a.id is not null;
五、交叉連線
交叉連線實際上就是表A與表B的笛卡爾乘積。
select * from a cross join b; select * from a, b;