星空网 > 软件开发 > 数据库

sql数据库的表连接方式图文详解

sql数据库表连接,主要分为:内连接外连接(左连接、右连接 、全连接)、交叉连接,今天统一整合一下,看看他们的区别。

 
首先建表填充值。
学生表:student(id,姓名,年龄,性别 )
sql数据库的表连接方式图文详解
sql数据库的表连接方式图文详解
成绩表:score(id,学生id,成绩)
sql数据库的表连接方式图文详解
sql数据库的表连接方式图文详解
 
一、内连接(inner join……on)
select student.* ,Score.* from student inner join Score on student.id=Score.sid

查询结果如下:
sql数据库的表连接方式图文详解
 
sql数据库的表连接方式图文详解
关系如下图:
sql数据库的表连接方式图文详解
 
sql数据库的表连接方式图文详解
总结: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

查询结果如下:
sql数据库的表连接方式图文详解
sql数据库的表连接方式图文详解
关系如下图:
sql数据库的表连接方式图文详解
sql数据库的表连接方式图文详解
总结: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
sql数据库的表连接方式图文详解

sql数据库的表连接方式图文详解
关系如下图:
sql数据库的表连接方式图文详解
sql数据库的表连接方式图文详解
总结:right join 以右表为准,查询出右表的所有数据,左表中有对应的则显示出来,没有对应的则显示为null.
 
(3)全连接(full join ……on)
select student.* ,Score.* from student full join Score on student.id=Score.sid
sql数据库的表连接方式图文详解

sql数据库的表连接方式图文详解
总结:full join 是为left和right的集合,某表中某一行在另一表中无匹配行,则相应列的内容为NULL。
 
三、交叉连接(cross join),注意没有on条件
select student.* ,Score.* from student cross join Score
sql数据库的表连接方式图文详解

sql数据库的表连接方式图文详解

叉联接也称作笛卡尔积。相当于两个表中的所有行进行排列组合。

若表a有X行,表b有Y行,则将返回XY行记录。


 
 
 
 
 
 



原标题:sql数据库的表连接方式图文详解

关键词:sql

sql
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流