菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
51
0

一张图搞定七种 JOIN 关系

原创
05/13 14:22
阅读数 1152

在 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关系

发表评论

0/200
51 点赞
0 评论
收藏
为你推荐 换一批