views:

58

answers:

2

Hi,

I'm learning SQL and I've written a query that returns all owners of Fords. How do I amend the query so that it doesn't return anyone who owns a Ford and a Ferarri?

SELECT  DISTINCT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ford' 

Added:

I tried the following code to see if I could produce just people who didn't own Ferarris, but it produces a blank datasheet. Any ideas what's wrong with it?

SELECT  DISTINCT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE NOT EXISTS
(SELECT  Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ferarri' )
+1  A: 

Since this is marked homework, here are some hints:

  • Find the Ids of all persons who own a Ferrari (should be almost identical to your original query)
  • Use this query in a sub-query (or join) to exclude them from your original query
Oded
Thanks. Some additional info on how to do step 2 would be great. I'm a real beginner!
Dave
@Dave - Perhaps this will help: http://allenbrowne.com/subquery-01.html
Oded
A: 
SELECT 

  FORDOWNERS.PID

FROM 

  (SELECT  DISTINCT Owns.Pid
  FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
  WHERE Car.Manufacturer = 'Ford') AS FORDOWNERS

INNER JOIN 

  (SELECT  DISTINCT Owns.Pid
  FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
  WHERE Car.Manufacturer = 'Ferrari') AS FERRARIOWNERS

ON FORDOWNERS.PID = FERRARIOWNERS.PID

or like this

SELECT 

  OWNS.PID

FROM 

  Person INNER JOIN Owns ON Person.Pid= Owns.Pid INNER JOIN Car ON Owns.Cid=Car.Cid
  WHERE Car.Manufacturer = 'Ford'
  AND OWNS.PID IN (SELECT  DISTINCT Owns.Pid
                   FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
                   WHERE Car.Manufacturer = 'Ferrari')
Parkyprg
@Parkyprg - when a question is marked homework we try to provide _hints_, not complete solutions. Why? Because otherwise how will the asker learn?
Oded
Thanks for this more complete answer. I tried both of them and they produced empty results. BTW, I'm looking for people who own Fords but DON'T own Ferarris.
Dave
Actually, I the problem was just my incorrect spelling of Ferrari. I just added a NOT in the right place and it worked. Thanks.
Dave
@Oded - you are right, I should thought about that.
Parkyprg