sql数据库的表连接方式图文详解
Posted 没有比脚更长的路
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql数据库的表连接方式图文详解相关的知识,希望对你有一定的参考价值。
sql数据库表连接,主要分为:内连接、外连接(左连接、右连接 、全连接)、交叉连接,今天统一整合一下,看看他们的区别。
首先建表填充值。
学生表:student(id,姓名,年龄,性别 )
![](https://image.cha138.com/20210611/8dd87de9ff0f4107bac4d064b19b2fc8.jpg)
成绩表:score(id,学生id,成绩)
![](https://image.cha138.com/20210611/1e4d5e66d33b4be8ae7e0a18e23bdd44.jpg)
一、内连接(inner join……on)
select student.* ,Score.* from student inner join Score on student.id=Score.sid
查询结果如下:
![](https://image.cha138.com/20210611/650d990564ed4b2aacf04fe5df993f8b.jpg)
关系如下图:
![](https://image.cha138.com/20210611/e941c53880934d5abdada7c4ec901058.jpg)
总结:inner join取两表的交集。
二、外连接
外连接包括 左连接、右连接、全连接 (left|right | full outer join ……on),其中outer可以省略
(1)左连接(left join ……on)
select student.* ,Score.* from student left join Score on student.id=Score.sid
查询结果如下:
![](https://image.cha138.com/20210611/61305fa1f55946d9b3b69dfd75107f12.jpg)
关系如下图:
![](https://image.cha138.com/20210611/7ed8bd2b04eb409f9de05f966ca7d99f.jpg)
总结:left join 以左表为准,查询出左表的所有数据,右表中有对应的则显示出来,没有对应的则显示为null.
注:A left join B on 与 A,B where 有相同效果,如下:
select student.* ,Score.* from student inner join Score on student.id=Score.sid
select student.* ,Score.* from student,Score where student.id=Score.sid
(2)右连接(right join ……on)
select student.* ,Score.* from student right join Score on student.id=Score.sid
![](https://image.cha138.com/20210611/0d66bd9ac0f4491bb8c909a5941fd988.jpg)
关系如下图:
![](https://image.cha138.com/20210611/c12339d7744e4addb1e5e0c61bd8de90.jpg)
总结:right join 以右表为准,查询出右表的所有数据,左表中有对应的则显示出来,没有对应的则显示为null.
(3)全连接(full join ……on)
select student.* ,Score.* from student full join Score on student.id=Score.sid
![](https://image.cha138.com/20210611/6e2106edd0ff47eab617eadc0ddb9daa.jpg)
总结:full join 是为left和right的集合,某表中某一行在另一表中无匹配行,则相应列的内容为NULL。
三、交叉连接(cross join),注意没有on条件
select student.* ,Score.* from student cross join Score
![](https://image.cha138.com/20210611/a3d686812dcd4b60a04bb73cc1a50c41.jpg)
叉联接也称作笛卡尔积。相当于两个表中的所有行进行排列组合。
若表a有X行,表b有Y行,则将返回XY行记录。
以上是关于sql数据库的表连接方式图文详解的主要内容,如果未能解决你的问题,请参考以下文章