日期:2014-05-19  浏览次数:20611 次

请教两条sql语句的不同.
语句一:
Select   A.*   From   A   Left   Join   B   On   A.Code   =   B.Code   And   B.Name   =   'CSDN '
语句二:
Select   A.*   From   A   Left   Join   B   On   A.Code   =   B.Code   Where   B.Name   =   'CSDN '

上面这两条语句的结果不相同,先求教大家错在哪里,为什么错?谢谢

------解决方案--------------------
前者的 B.Name = 'CSDN ' 作用于 join 过程是否匹配的判断
后者的 B.Name = 'CSDN ' 作用于 join 结果集上的判断

两者已经是不同的处理过程了,结果不一样当然是很自然的事
------解决方案--------------------
很大區別。

一個是關聯的條件,一個是查詢的條件。

但是如果這裡將lEFT JOIN換成INNER JOIN,效果就是一樣的了。
------解决方案--------------------
关联的时候是默认ansi_nulls on 的 就是说 B.Name = 'CSDN ' 但B.Name 为null时是不成的
但ansi_nulls off 时 where 后面B.Name = 'CSDN ' 是成立的
没有举例,我说的对吗
------解决方案--------------------
语句一:
Select A.* From A Left Join B On A.Code = B.Code And B.Name = 'CSDN '
在关联条件的时候判断,加了and 就是有不但而且,条件比一般苛刻!
语句二:
Select A.* From A Left Join B On A.Code = B.Code Where B.Name = 'CSDN '
sql语句执行完成返回结果集(临时表)后判断!

各位高手,各位牛人,帮回答个问题,如有相关资料请附了,谢谢!
http://community.csdn.net/Expert/topic/5696/5696608.xml?temp=.5177881
------解决方案--------------------
第一句B.Name = 'CSDN '只是跟在left join 后面做关联条件,如果条件不匹配,left join 只会让右边为空,而不会去减少左边的记录数
第二句就完全不一样了B.Name = 'CSDN '跟在了where 后面,where 会无情地杀掉所有不合条件的记录,所以和第一句的结果就不一样了
------解决方案--------------------
举个例子给你看就可以了
declare @A table(
code varchar(5),
name varchar(10)
)
declare @B table(
code varchar(5),
name varchar(10)
)
insert into @A select '001 ', 'aaa '
union all select '002 ', 'csdn '
union all select '003 ', 'ccc '
union all select '004 ', 'ddd '
insert into @B select '001 ', 'csdn '
union all select '002 ', 'aaa '
union all select '003 ', 'bbb '
--select * from @A
--select * from @B
select a.* from @A a
left join @B b on a.code=b.code and b.name= 'csdn '
select a.* from @A a
left join @B b on a.code=b.code
where b.name= 'csdn '
--结果(第一个)
001 aaa
002 csdn
003 ccc
004 ddd
(第二个)
001 aaa


------解决方案--------------------
关联的时候是默认ansi_nulls on 的 就是说 B.Name = 'CSDN ' 在关联时B.Name 为null时是不成的(不太肯定)

但ansi_nulls off 时 where 后面 B.Name 为null时 B.Name = 'CSDN ' 是成立的(其实不是成立就是返回Null时sql当 true来处理了)
手头还有工作,等下做测试

说明白了吧
------------------------------
我来测试:

create table #t1 (id1 int,col1 varchar(20))
insert into #t1
select 1, 'aaa1 ' union all
select 2, 'bbb1 ' union all
select 3, 'ccc1 ' union all
select 4, 'CSDN ' union all
select 5, 'CSDN '


create table #t2 (id2 int,col2 varchar(20))
insert into #t2
select 1, 'aaa2 ' union all
select 2, 'bbb2 ' union all
select 3, 'ccc2 ' union all
select 4, 'CSDN ' union all
select 5, null union all
select 6, null


create table #t3 (id3 int,col3 varchar(20))