首页 > 其他 > 详细

内连接和外连接

时间:2014-08-15 12:55:18      阅读:295      评论:0      收藏:0      [点我收藏+]
--------------------------------------------------------------------
内连接
--------------------------------------------------------------------
内连接就是两张表都只显示符合连接条件的行。
举例1:
假设有两个Excel报表:出货表和产品表
出货表:
日期 客户 产品编码 数量
2003-10-20 永华公司 1001 10
2003-10-21 风貌公司 1002 20
产品表:
产品编码 产品名称 生产厂家
1001 PC机 创成公司
1002 打印机 风华公司
内连接条件为:出货表.产品编码=产品表.产品编码
内连接的结果集为:
日期 客户 产品编号 数量 产品名称 生产厂家
2003-10-20 永华公司 1001 10 PC机 创成公司
2003-10-21 风貌公司 1002 20 打印机 风华公司

举例2:
Book表
BookId BookName StudentId
1 《培训》 3
2 《成功秘诀》 5
3 《红楼梦》 3
4 《西厢记》 2
5 《水浒传》 6
6 《三国演义》 10

Student表
StudentId StudentName
1 张三
2 李四
3 关羽
4 张飞
5 黄聪
6 李逵
7 赵娜
8 王敏
NULL NULL

内连接查询:

select from [Book] as b,[Student] as s where b.StudentId=s.StudentId

 等价于如下(也可以不要关键字inner,此为系统默认)

select from [Book] as b inner join [Student] as s ON b.StudentId=s.StudentId


内连接查询结果:
BookId BookName StudentId StudentName
4 《西厢记》 2 李四
1 《培训》 3 关羽
3 《红楼梦》 3 关羽
2 《成功秘诀》 5 黄聪
5 《水浒传》 6 李逵


-----------------------------------------------------------------------
外连接
-----------------------------------------------------------------------
左外连接查询:

select from [Book] as b left join [Student] as s ON b.StudentId=s.StudentId


查询结果:

BookId BookName StudentId StudentId StudentName
1 《培训》 3 3 关羽
2 《成功秘诀》 5 5 黄聪
3 《红楼梦》 3 3 关羽
4 《西厢记》 2 2 李四
5 《水浒传》 6 6 李逵
6 《三国演义》 10 NULL NULL

执行过程:

即以from [Book] left join [Student]Book表为基准,即以Book(b)b.StudentId为基准。遍历Student(s)中与之匹配的b.StudentId。若b.StudentId含有s.StudentId匹配项,则进行拼接,然后遍历Student表的下一条s.StudentId,当查询完毕则进入下一条b.StudentId。若b.StudentId没有相应s.StudentId匹配项时,则显示左表的项,拼接右表的项显示为NULL



内连接和外连接,布布扣,bubuko.com

内连接和外连接

原文:http://blog.csdn.net/yrp_ssdut/article/details/38581167

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!