一, 开头说
不出意外, 还是先说下 SQL 中所有的联接类型:
内连接, 外连接 (左连接, 右连接 , 全连接), 交叉连接
然后接下来就是依次学习下各种连接的使用效果
二, 各种连接秀
首先准备两张表
学生表: student(id, 姓名, 年龄, 性别 )
成绩表: score(id, 学生 id, 成绩)
1, 内连接 inner join......on
select student.* ,Score.* from student inner join Score on student.id=Score.sid
查询结果如下:
关系如下图:
总结: inner join 取两表的交集.
2, 外连接
外连接包括 左连接, 右连接, 全连接 (left|right | full outer join ......on), 其中 outer 可以省略
(1) 左连接 (left join ......on)
select student.* ,Score.* from student left join Score on student.id=Score.sid
查询结果如下:
关系如下图:
总结: 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
关系如下图:
总结: right join 以右表为准, 查询出右表的所有数据, 左表中有对应的则显示出来, 没有对应的则显示为 null.
(3) 全连接 (full join ......on)
select student.* ,Score.* from student full join Score on student.id=Score.sid
总结: full join 是为 left 和 right 的集合, 某表中某一行在另一表中无匹配行, 则相应列的内容为 NULL.
3,
交叉连接 (cross join), 注意没有 on 条件
select student.* ,Score.* from student cross join Score
叉联接也称作笛卡尔积. 相当于两个表中的所有行进行排列组合.
若表 a 有 X 行, 表 b 有 Y 行, 则将返回 XY 行记录.
说明: 使用 select * from student,Score 语句时, 同样会做笛卡尔积生成虚拟表然后查询会所有条数据
来源: http://www.bubuko.com/infodetail-3025202.html