+ -
当前位置:首页 → 问答吧 → 差点迷糊- -

差点迷糊- -

时间:2011-11-18

来源:互联网

SQL code
--> 测试数据: [tba]
if object_id('[tba]') is not null drop table [tba]
create table [tba] (col1 int)
insert into [tba]
select 1 union all
select 2 union all
select 3
--> 测试数据: [tbb]
if object_id('[tbb]') is not null drop table [tbb]
create table [tbb] (col1 int,col2 varchar(1))
insert into [tbb]
select 1,'a' union all
select 2,'a' union all
select 3,'b'

--开始查询
select * from [tba] a left join [tbb] b on (a.col1=b.col1 and b.col2='a')

/*
col1        col1        col2
----------- ----------- ----
1           1           a
2           2           a
3           NULL        NULL

(3 行受影响)
*/

select * from [tba] a left join [tbb] b on (a.col1=b.col1) where b.col2='a'

/*
col1        col1        col2
----------- ----------- ----
1           1           a
2           2           a

(2 行受影响)
*/

--结束查询
drop table [tba],[tbb]


。。。

作者: geniuswjt   发布时间: 2011-11-18

SQL code
select * from [tba] a left join [tbb] b on (a.col1=b.col1 and b.col2='a')

--相当于

select * from [tba] a left join (select * from [tbb] where b.col2='a') b on a.col1=b.col1

作者: ssp2009   发布时间: 2011-11-18

?炫耀贴?

作者: fredrickhu   发布时间: 2011-11-18

select * from [tba] a left join [tbb] b on (a.col1=b.col1) where b.col2='a'

這樣等同於inner join ,因where有別名b的條件,沒去null

作者: roy_88   发布时间: 2011-11-18

不是炫耀贴,是mark帖。
刚才迷迷糊糊写了个比较长的left语句,结果出来的条数怎么看都是inner join的结果
排查了半天才发现。。。
是1楼和3楼的意思。下次要小心了。

作者: geniuswjt   发布时间: 2011-11-18


语句执行顺序,where在on之后,where 对on之后的结果集进行了筛选,所以结果不一样。。
---我这样理解对吗?

作者: jwdream2008   发布时间: 2011-11-18

嗯,如果col2在左表而不在右表的话这两条的结果就一样了,但是顺序当然还是对的
引用 5 楼 jwdream2008 的回复:
语句执行顺序,where在on之后,where 对on之后的结果集进行了筛选,所以结果不一样。。
---我这样理解对吗?

作者: geniuswjt   发布时间: 2011-11-18

值得注意下。。

作者: TimZhuFaith   发布时间: 2011-11-18