一張圖搞定七種 JOIN 關係

zhangdeTalk發表於2019-12-24

在 mysql 查詢語句中,JOIN 扮演的角色很重要,所以掌握其用法很重要。很多同學可能只是會用幾種常用的,但要成為高階的工程師是需要掌握透徹,360度全無死角。

圖片精華版

一張圖搞定七種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關係

阿德

相關文章