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