關於在SQL語句中ON和WHERE中條件使用的差異

bq_wang發表於2008-08-31
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE測試條件如下

create table customers
(
customerid char(5),
city varchar(10)
);
go
create table orders
(
orderid int,
customerid char(5)
);
go
insert into customers values('FISSA','Madrid');
insert into customers values('FRNDO','Madrid');
insert into customers values('KRLOS','Madrid');
insert into customers values('MRPHS','Zion');

insert into orders values(1,'FRNDO');
insert into orders values(2,'FRNDO');
insert into orders values(3,'KRLOS');
insert into orders values(4,'KRLOS');
insert into orders values(5,'KRLOS');
insert into orders values(6,'MRPHS');
insert into orders values(7,NULL);

select c.customerid,o.customerid,c.city,o.orderid as numorders
from customers as c
left outer join orders as o
on c.customerid=o.customerid  and c.city='Madrid'

select c.customerid,o.customerid,c.city,o.orderid as numorders
from customers as c
left outer join orders as o
on c.customerid=o.customerid  
where c.city='Madrid'

 

查詢情況

select * from customers
FISSA    Madrid
FRNDO    Madrid
KRLOS    Madrid
MRPHS    Zion

select * from orders
1    FRNDO
2    FRNDO
3    KRLOS
4    KRLOS
5    KRLOS
6    MRPHS
7    NULL

select c.customerid,o.customerid,c.city,o.orderid as numorders
from customers as c
left outer join orders as o
on c.customerid=o.customerid  and c.city='Madrid'
FISSA    NULL    Madrid    NULL
FRNDO    FRNDO    Madrid    1
FRNDO    FRNDO    Madrid    2
KRLOS    KRLOS    Madrid    3
KRLOS    KRLOS    Madrid    4
KRLOS    KRLOS    Madrid    5
MRPHS    NULL    Zion    NULL

select c.customerid,o.customerid,c.city,o.orderid as numorders
from customers as c
left outer join orders as o
on c.customerid=o.customerid  
where c.city='Madrid'
FISSA    NULL    Madrid    NULL
FRNDO    FRNDO    Madrid    1
FRNDO    FRNDO    Madrid    2
KRLOS    KRLOS    Madrid    3
KRLOS    KRLOS    Madrid    4
KRLOS    KRLOS    Madrid    5

SQLServer2005中的查詢中,SQLServer對查詢語句的解析順序如下:

1.         SQLServer先按照From表進行笛卡爾乘積

即對customerorder做笛卡爾乘積,得到一個28行的虛擬表,以上兩條SQL語句是完全一致的。

2.         然後按照ON的順序校驗True/False

對笛卡爾乘積的結果進行True/False判斷,即對on c.customerid=o.customerid  on c.customerid=o.customerid  and c.city='Madrid',實際上從結果上看這兩條語句沒什麼不同,主要是後者的c.city=’Madrid’未起到任何作用。

3.         然後進行Left Outer操作

Left Outer環節中,因為都是使用customer為基表,在此結果中又把客戶MRPHS加了回來,這就是第一條語句會多出來一條記錄的原因。

4.         然後進行Where條件解析

第一條語句沒有where條件,而第二條語句繼續進行where語句解析,又把客戶MRPHS刪除了。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/6517/viewspace-439084/,如需轉載,請註明出處,否則將追究法律責任。

相關文章