如何在SQL中展示不拥有法拉利的福特车主

时间:2010-09-24 09:22:45

标签: sql ms-access

我正在学习SQL,并且我编写了一个返回所有Fords所有者的查询。如何修改查询,使其不归还拥有福特和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' 

添加了:

我尝试了以下代码,看看我是否可以只生产没有Ferarris的人,但它会生成一个空白的数据表。有什么想法吗?

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' )

2 个答案:

答案 0 :(得分:1)

由于这是标记的作业,这里有一些提示:

  • 查找拥有法拉利的所有人的ID(应与原始查询几乎相同)
  • 在子查询(或联接)中使用此查询以将其从原始查询中排除

答案 1 :(得分:0)

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

或者像这样

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')