TSQL了解Query的执行情况

时间:2010-09-10 19:05:24

标签: sql-server-2005

我有两张桌子

Table Visitor
ID Name    CityName
1  Jon     NY 
1  Jon     KY
2  Paul    NY
1  paul    TY

Table City
ID     CityName
1      NY  
2      KY
3      TY

我必须列出访问过City Table所有城市的访客。

我从网上接受了查询,但我不知道它是如何在内部工作的。

查询

select distinct v1.name from Visitor v1 
where not exists
          (
             select c.CityName from City c
             where not exists 
              (
                select v2.CityName from visitor v2 where
                v2.CityName=c.CityName and v1.Name=v2.Name
              )  
         )

Kinldy帮助我理解这一步

迭代1

Most outer query  v1.Name=jon 

outer query       c.CityName=NY

inner query       V2.CityName = c.CityName (NY=NY)
                  and v1.Name=v2.Name (Jon =Jon)

inner query return valye (i.e) v2.CityName=NY

NY not exists
(          
  NY
)

consition失败,所以没有回复

迭代2

    Most outer query  v1.Name=jon 

    outer query       c.CityName=NY

    inner query       V2.CityName = c.CityName (KY=NY)
                      and v1.Name=v2.Name (Jon =Jon)

    inner query return valye (i.e) v2.CityName=NULL

NY not exists
(          
  NULL
)

condition fails 
(i.e) NOT Exists is true so Jon is returned  from outer most query.

我理解正确吗?

2 个答案:

答案 0 :(得分:1)

这是Chris Date推广的relational division query

它基本上使用双阴性。用英语改写它的作用:它选择没有城市的所有访客,他们没有访问过。

答案 1 :(得分:0)

仅供参考,一种更简单的方法是:

select v1.name 
from Visitor v
inner join City c on v.CityName = c.CityName
group by v1.Name
having count(distinct(c.CityName)) = 3