专业的编程技术博客社区

网站首页 > 博客文章 正文

一张图搞定七种 JOIN 关系(培训需求调研不是一张问卷搞定)

baijin 2024-08-27 11:22:30 博客文章 3 ℃ 0 评论

在 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.idunion 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 nullunionselect 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;

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表