이 쿼리의 결과는 뭘까요?
select *
from tblx a
left join tbly b
on a.idx = b.idx
and a.idx in (1,2)
and b.col1 = 10
이거라고 생각하는가?
if object_id('tblx') is not null
drop table tblx
go
if object_id('tbly') is not null
drop table tbly
go
create table tblx
(idx int
,col1 int
,col2 int
)
go
insert into tblx values (1,10,100)
insert into tblx values (2,20,200)
insert into tblx values (3,30,300)
insert into tblx values (4,40,400)
insert into tblx values (5,50,500)
go
create table tbly
(idx int
,col1 int
,col2 int
)
go
insert into tbly values (1,10,100)
insert into tbly values (2,20,200)
insert into tbly values (3,30,300)
go
내가 위 질문을 했을때 10명에 1명도 답을 못하더라....... 이는 sql join 의 on 과 where 를 아직도 이해하지 못하고 마구 쓰는 사람이 대부분 이라는 것이다. 심심하면 당신이 일하는 회사의 sql 팀장에게 문의해 봐라....모르는 사람도 있을듯 하다.
create database l
go
use l
go
if object_id ('tblx') is not null
drop table tblx
go
create table tblx
(idx int
,c1 int
,c2 int
)
go
if object_id ('tbly') is not null
drop table tbly
go
create table tbly
(idx int
,c1 int
,c2 int
)
go
insert into tblx values (1,1,1),(2,2,1),(3,null,1),(4,4,null)
insert into tbly values (1,1,1),(2,2,1),(4,4,null)
go
--exec sp_dbcmptlevel l, 80
select *
from tblx a, tbly b
where a.idx *= b.idx
and (b.idx = 1 or b.idx is null)
이건 이렇게 풀 수 있다.
select *
from tblx a
left join tbly b
on a.idx = b.idx
and (b.idx = 1 or b.idx is null)
다음의 경우를 생각해 보자.
select *
from tblx a
left join tbly b
on a.idx = b.idx
where b.idx = 1
or b.idx is null
위 쿼리를 tsql 조인으로 해보라 결과가 나오지 않는다.
select *
from tblx a, tbly b
where a.idx *= b.idx
and (b.idx = 1 or b.idx is null)
이렇게 풀 수 밖에 없다. 이건 불편하다.
select *
from (select a.*, b.idx bidx, b.c1 bc1, b.c2 bc2
from tblx a, tbly b
where a.idx *= b.idx) a
where bidx = 1 or bidx is null
정의를 내려보면 다음과 같다.
'밥벌이' 카테고리의 다른 글
부하 데이터생성 (0) | 2010.11.18 |
---|---|
Array Insert (1) | 2010.11.17 |
insert select 로 인해 플랜 공간이 소모됩니다. (0) | 2010.10.28 |
insert 속도를 높여보자 (1) | 2010.10.18 |
.net framework 의 sql native client 를 이용할 경우 sp_reset_connection (4) | 2010.10.18 |
- ansi left outer join 에서 on 절에는 join 조건을 기술하고 where 조건은 필터를 표시한다. 그러므로 어떠한 경우에도 명확하게 표현할 수 있다.
- tsql *= (left join) 은 driving table 의 조건은 filter 조건이고, drived 되는 테이블의 조건은 join 조건으로만 풀려 drived 되는 테이블을 필터로 풀 수 없는 문제가 있게된다. 이러한 불편을 해소하기 위해 tsql *= (outer join) 을 sql 서버에서 차기 버전부터 지원하지 않기로 한 것이다. work around 로 tsql *= 에서 inline view 를 같이 쓰면 drived 되는 테이블의 filter 조건을 명시 할 수 있다.
- 따라서 이것을 누구처럼 먼저하고 저것을 먼저하고 라고 해석하면 안된다.