探讨使用外联接(OUTER JOIN)联接两表时容易忽略的一个小问题

来源:互联网 发布:在linux上面安装jira 编辑:程序博客网 时间:2024/05/09 22:10

文章使用的实例表

班级表

 

表2 学生表

 

 

文章探讨问题说明

请说出下面两组查询的结果是什么?

查询1

select * from tb_Class a left join tb_Student b on a.classid=b.classid where b.score<=90

查询2

select * from tb_Class a left join tb_Student b on a.classid=b.classid and b.score<=90

注:本文以左外联接为例。

 

问题解答

查询1与查询2仅一词之别,查询1中的“where”在查询2中变成了“and”。形式上的差别不大,但是返回结果却相差很大。下面给出查询结果。

查询1结果

查询2结果

 

从查询结果,可以看出:

查询1先用tb_Class表左联接tb_Student表,再在联接后的结果中筛选出“b.score<=90”的记录;

查询2先从tb_Student表中筛选出“b.score<=90”的记录,再用tb_Class表与其进行左连接操作。


说点别的

下面,再来补充说明一下另外一个容易被忽视的小问题。

直接给出SQL脚本,你能直接说出最终查询得的记录的条数吗?

declare @a table(id int not null,name nvarchar(3) not null,primary key(id));declare @b table(id int not null,name nvarchar(3) not null,primary key(id));insert into @a values(1,'a'),(2,'b'),(3,'c')insert into @b values(1,'a1'),(2,'b1'),(3,'c1')select * from @a a left join @b b on a.id=1 
执行结果是:

为什么呢?

原因出在a.ID=1。

总结

小知识点,但是很容易被忽略,望大家引起注意哦。

原创粉丝点击