在 mysql 查詢語句中,JOIN 扮演的角色很重要,所以掌握其用法很重要。很多同學可能只是會用幾種常用的,但要成為高階的工程師是需要掌握透徹,360度全無死角。
圖片精華版
文字解釋版
1. 需要準備好兩個table:subject(學科表)和 student_score(學生成績表)
通過學生成績表的subject_id欄位(學科ID)和學科表的id欄位(主鍵ID)進行關聯
2. 分別填充資料
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;
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;
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;
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;
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;
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;
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;