views:

23

answers:

2

I have two tables

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

I have to list the visitor who has visited all cities in City Table.

I took the query from web,but i do not the how it works internally.

The query is

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 help me to understand the step

Iteration 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 fails so nothing return

Iteration 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.

Am i right in understanding?

+1  A: 

This is the relational division query popularised by Chris Date.

It basically uses a double negative. To rewrite what it is doing in English: It Selects all the Visitors where there is no city that they have not visited.

Martin Smith
Excellent link to read and understand the query.
Amit
A: 

FYI, a simpler approach is:

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
RedFilter