一张图搞定MySQL七种 JOIN 关系

在 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;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VAtABLgH-1577718684574)(https://cdn.learnku.com/uploads/images/201912/24/32495/ZUzDjBNBDe.png!large)]

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;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L3PcaQY8-1577718684575)(https://cdn.learnku.com/uploads/images/201912/24/32495/gC6Gu6upDx.png!large)]

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值