一張圖搞定七種 JOIN 關係

在 mysql 查詢語句中,JOIN 扮演的角色很重要,因此掌握其用法很重要。不少同窗可能只是會用幾種經常使用的,但要成爲高級的工程師是須要掌握透徹,360度全無死角。mysql

圖片精華版

一張圖搞定七種JOIN關係

文字解釋版

1. 須要準備好兩個table:subject(學科表)和 student_score(學生成績表)
經過學生成績表的subject_id字段(學科ID)和學科表的id字段(主鍵ID)進行關聯
複製代碼

一張圖搞定七種JOIN關係

一張圖搞定七種JOIN關係

2. 分別填充數據 
複製代碼

一張圖搞定七種JOIN關係

一張圖搞定七種JOIN關係

3. inner join
語句:select score.student_name,score.score,subject.name,subject.teacher from student_score as score inner join subject on score.subject_id = subject.id;
複製代碼

一張圖搞定七種JOIN關係

4. left join (共有+右表不匹配補NULL)
語句:select score.student_name,score.score,subject.name,subject.teacher from student_score as score left join subject on score.subject_id = subject.id;
複製代碼

一張圖搞定七種JOIN關係

5. left join (左表獨有)
語句:select score.student_name,score.score,subject.name,subject.teacher from student_score as score left join subject on score.subject_id = subject.id where subject.id is null;
複製代碼

一張圖搞定七種JOIN關係

6. right join (共有+左表不匹配補NULL)
語句:select score.student_name,score.score,subject.name,subject.teacher from student_score as score right join subject on score.subject_id = subject.id;
複製代碼

一張圖搞定七種JOIN關係

7. right join (右表獨有)
語句:select score.student_name,score.score,subject.name,subject.teacher from student_score as score right join subject on score.subject_id = subject.id where score.id is null;
複製代碼

一張圖搞定七種JOIN關係

8. union (左右表合併並去重)
語句:
select score.student_name,score.score,subject.name,subject.teacher from student_score as score left join subject on score.subject_id = subject.id
union 
select score.student_name,score.score,subject.name,subject.teacher from student_score as score right join subject on score.subject_id = subject.id;
複製代碼

一張圖搞定七種JOIN關係

9. union (左右表獨有)
語句:
select score.student_name,score.score,subject.name,subject.teacher from student_score as score left join subject on score.subject_id = subject.id where subject.id is null
union
select score.student_name,score.score,subject.name,subject.teacher from student_score as score right join subject on score.subject_id = subject.id where score.id is null;
複製代碼

一張圖搞定七種JOIN關係
相關文章
相關標籤/搜索